SemaChecking.cpp 559 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements extra semantic analysis beyond what is enforced
  10. // by the C type system.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/APValue.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/AttrIterator.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/ExprOpenMP.h"
  28. #include "clang/AST/FormatString.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/NonTrivialTypeVisitor.h"
  31. #include "clang/AST/OperationKinds.h"
  32. #include "clang/AST/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Basic/AddressSpaces.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/OpenCLOptions.h"
  44. #include "clang/Basic/OperatorKinds.h"
  45. #include "clang/Basic/PartialDiagnostic.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/Specifiers.h"
  49. #include "clang/Basic/SyncScope.h"
  50. #include "clang/Basic/TargetBuiltins.h"
  51. #include "clang/Basic/TargetCXXABI.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TypeTraits.h"
  54. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  55. #include "clang/Sema/Initialization.h"
  56. #include "clang/Sema/Lookup.h"
  57. #include "clang/Sema/Ownership.h"
  58. #include "clang/Sema/Scope.h"
  59. #include "clang/Sema/ScopeInfo.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Sema/SemaInternal.h"
  62. #include "llvm/ADT/APFloat.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallBitVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallString.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/SaveAndRestore.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include <algorithm>
  89. #include <cassert>
  90. #include <cstddef>
  91. #include <cstdint>
  92. #include <functional>
  93. #include <limits>
  94. #include <string>
  95. #include <tuple>
  96. #include <utility>
  97. using namespace clang;
  98. using namespace sema;
  99. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  100. unsigned ByteNo) const {
  101. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  102. Context.getTargetInfo());
  103. }
  104. /// Checks that a call expression's argument count is the desired number.
  105. /// This is useful when doing custom type-checking. Returns true on error.
  106. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  107. unsigned argCount = call->getNumArgs();
  108. if (argCount == desiredArgCount) return false;
  109. if (argCount < desiredArgCount)
  110. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  111. << 0 /*function call*/ << desiredArgCount << argCount
  112. << call->getSourceRange();
  113. // Highlight all the excess arguments.
  114. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  115. call->getArg(argCount - 1)->getEndLoc());
  116. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  117. << 0 /*function call*/ << desiredArgCount << argCount
  118. << call->getArg(1)->getSourceRange();
  119. }
  120. /// Check that the first argument to __builtin_annotation is an integer
  121. /// and the second argument is a non-wide string literal.
  122. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  123. if (checkArgCount(S, TheCall, 2))
  124. return true;
  125. // First argument should be an integer.
  126. Expr *ValArg = TheCall->getArg(0);
  127. QualType Ty = ValArg->getType();
  128. if (!Ty->isIntegerType()) {
  129. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  130. << ValArg->getSourceRange();
  131. return true;
  132. }
  133. // Second argument should be a constant string.
  134. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  135. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  136. if (!Literal || !Literal->isAscii()) {
  137. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  138. << StrArg->getSourceRange();
  139. return true;
  140. }
  141. TheCall->setType(Ty);
  142. return false;
  143. }
  144. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  145. // We need at least one argument.
  146. if (TheCall->getNumArgs() < 1) {
  147. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  148. << 0 << 1 << TheCall->getNumArgs()
  149. << TheCall->getCallee()->getSourceRange();
  150. return true;
  151. }
  152. // All arguments should be wide string literals.
  153. for (Expr *Arg : TheCall->arguments()) {
  154. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  155. if (!Literal || !Literal->isWide()) {
  156. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  157. << Arg->getSourceRange();
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  164. /// result type to the corresponding pointer type.
  165. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  166. if (checkArgCount(S, TheCall, 1))
  167. return true;
  168. ExprResult Arg(TheCall->getArg(0));
  169. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  170. if (ResultType.isNull())
  171. return true;
  172. TheCall->setArg(0, Arg.get());
  173. TheCall->setType(ResultType);
  174. return false;
  175. }
  176. /// Check the number of arguments, and set the result type to
  177. /// the argument type.
  178. static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
  179. if (checkArgCount(S, TheCall, 1))
  180. return true;
  181. TheCall->setType(TheCall->getArg(0)->getType());
  182. return false;
  183. }
  184. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  185. if (checkArgCount(S, TheCall, 3))
  186. return true;
  187. // First two arguments should be integers.
  188. for (unsigned I = 0; I < 2; ++I) {
  189. ExprResult Arg = TheCall->getArg(I);
  190. QualType Ty = Arg.get()->getType();
  191. if (!Ty->isIntegerType()) {
  192. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  193. << Ty << Arg.get()->getSourceRange();
  194. return true;
  195. }
  196. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  197. S.getASTContext(), Ty, /*consume*/ false);
  198. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  199. if (Arg.isInvalid())
  200. return true;
  201. TheCall->setArg(I, Arg.get());
  202. }
  203. // Third argument should be a pointer to a non-const integer.
  204. // IRGen correctly handles volatile, restrict, and address spaces, and
  205. // the other qualifiers aren't possible.
  206. {
  207. ExprResult Arg = TheCall->getArg(2);
  208. QualType Ty = Arg.get()->getType();
  209. const auto *PtrTy = Ty->getAs<PointerType>();
  210. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  211. !PtrTy->getPointeeType().isConstQualified())) {
  212. S.Diag(Arg.get()->getBeginLoc(),
  213. diag::err_overflow_builtin_must_be_ptr_int)
  214. << Ty << Arg.get()->getSourceRange();
  215. return true;
  216. }
  217. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  218. S.getASTContext(), Ty, /*consume*/ false);
  219. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  220. if (Arg.isInvalid())
  221. return true;
  222. TheCall->setArg(2, Arg.get());
  223. }
  224. return false;
  225. }
  226. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  227. if (checkArgCount(S, BuiltinCall, 2))
  228. return true;
  229. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  230. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  231. Expr *Call = BuiltinCall->getArg(0);
  232. Expr *Chain = BuiltinCall->getArg(1);
  233. if (Call->getStmtClass() != Stmt::CallExprClass) {
  234. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  235. << Call->getSourceRange();
  236. return true;
  237. }
  238. auto CE = cast<CallExpr>(Call);
  239. if (CE->getCallee()->getType()->isBlockPointerType()) {
  240. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  241. << Call->getSourceRange();
  242. return true;
  243. }
  244. const Decl *TargetDecl = CE->getCalleeDecl();
  245. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  246. if (FD->getBuiltinID()) {
  247. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  248. << Call->getSourceRange();
  249. return true;
  250. }
  251. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  252. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  253. << Call->getSourceRange();
  254. return true;
  255. }
  256. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  257. if (ChainResult.isInvalid())
  258. return true;
  259. if (!ChainResult.get()->getType()->isPointerType()) {
  260. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  261. << Chain->getSourceRange();
  262. return true;
  263. }
  264. QualType ReturnTy = CE->getCallReturnType(S.Context);
  265. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  266. QualType BuiltinTy = S.Context.getFunctionType(
  267. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  268. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  269. Builtin =
  270. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  271. BuiltinCall->setType(CE->getType());
  272. BuiltinCall->setValueKind(CE->getValueKind());
  273. BuiltinCall->setObjectKind(CE->getObjectKind());
  274. BuiltinCall->setCallee(Builtin);
  275. BuiltinCall->setArg(1, ChainResult.get());
  276. return false;
  277. }
  278. /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
  279. /// __builtin_*_chk function, then use the object size argument specified in the
  280. /// source. Otherwise, infer the object size using __builtin_object_size.
  281. void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
  282. CallExpr *TheCall) {
  283. // FIXME: There are some more useful checks we could be doing here:
  284. // - Analyze the format string of sprintf to see how much of buffer is used.
  285. // - Evaluate strlen of strcpy arguments, use as object size.
  286. if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
  287. isConstantEvaluated())
  288. return;
  289. unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
  290. if (!BuiltinID)
  291. return;
  292. unsigned DiagID = 0;
  293. bool IsChkVariant = false;
  294. unsigned SizeIndex, ObjectIndex;
  295. switch (BuiltinID) {
  296. default:
  297. return;
  298. case Builtin::BI__builtin___memcpy_chk:
  299. case Builtin::BI__builtin___memmove_chk:
  300. case Builtin::BI__builtin___memset_chk:
  301. case Builtin::BI__builtin___strlcat_chk:
  302. case Builtin::BI__builtin___strlcpy_chk:
  303. case Builtin::BI__builtin___strncat_chk:
  304. case Builtin::BI__builtin___strncpy_chk:
  305. case Builtin::BI__builtin___stpncpy_chk:
  306. case Builtin::BI__builtin___memccpy_chk: {
  307. DiagID = diag::warn_builtin_chk_overflow;
  308. IsChkVariant = true;
  309. SizeIndex = TheCall->getNumArgs() - 2;
  310. ObjectIndex = TheCall->getNumArgs() - 1;
  311. break;
  312. }
  313. case Builtin::BI__builtin___snprintf_chk:
  314. case Builtin::BI__builtin___vsnprintf_chk: {
  315. DiagID = diag::warn_builtin_chk_overflow;
  316. IsChkVariant = true;
  317. SizeIndex = 1;
  318. ObjectIndex = 3;
  319. break;
  320. }
  321. case Builtin::BIstrncat:
  322. case Builtin::BI__builtin_strncat:
  323. case Builtin::BIstrncpy:
  324. case Builtin::BI__builtin_strncpy:
  325. case Builtin::BIstpncpy:
  326. case Builtin::BI__builtin_stpncpy: {
  327. // Whether these functions overflow depends on the runtime strlen of the
  328. // string, not just the buffer size, so emitting the "always overflow"
  329. // diagnostic isn't quite right. We should still diagnose passing a buffer
  330. // size larger than the destination buffer though; this is a runtime abort
  331. // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
  332. DiagID = diag::warn_fortify_source_size_mismatch;
  333. SizeIndex = TheCall->getNumArgs() - 1;
  334. ObjectIndex = 0;
  335. break;
  336. }
  337. case Builtin::BImemcpy:
  338. case Builtin::BI__builtin_memcpy:
  339. case Builtin::BImemmove:
  340. case Builtin::BI__builtin_memmove:
  341. case Builtin::BImemset:
  342. case Builtin::BI__builtin_memset: {
  343. DiagID = diag::warn_fortify_source_overflow;
  344. SizeIndex = TheCall->getNumArgs() - 1;
  345. ObjectIndex = 0;
  346. break;
  347. }
  348. case Builtin::BIsnprintf:
  349. case Builtin::BI__builtin_snprintf:
  350. case Builtin::BIvsnprintf:
  351. case Builtin::BI__builtin_vsnprintf: {
  352. DiagID = diag::warn_fortify_source_size_mismatch;
  353. SizeIndex = 1;
  354. ObjectIndex = 0;
  355. break;
  356. }
  357. }
  358. llvm::APSInt ObjectSize;
  359. // For __builtin___*_chk, the object size is explicitly provided by the caller
  360. // (usually using __builtin_object_size). Use that value to check this call.
  361. if (IsChkVariant) {
  362. Expr::EvalResult Result;
  363. Expr *SizeArg = TheCall->getArg(ObjectIndex);
  364. if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
  365. return;
  366. ObjectSize = Result.Val.getInt();
  367. // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
  368. } else {
  369. // If the parameter has a pass_object_size attribute, then we should use its
  370. // (potentially) more strict checking mode. Otherwise, conservatively assume
  371. // type 0.
  372. int BOSType = 0;
  373. if (const auto *POS =
  374. FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
  375. BOSType = POS->getType();
  376. Expr *ObjArg = TheCall->getArg(ObjectIndex);
  377. uint64_t Result;
  378. if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
  379. return;
  380. // Get the object size in the target's size_t width.
  381. const TargetInfo &TI = getASTContext().getTargetInfo();
  382. unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
  383. ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
  384. }
  385. // Evaluate the number of bytes of the object that this call will use.
  386. Expr::EvalResult Result;
  387. Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
  388. if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
  389. return;
  390. llvm::APSInt UsedSize = Result.Val.getInt();
  391. if (UsedSize.ule(ObjectSize))
  392. return;
  393. StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
  394. // Skim off the details of whichever builtin was called to produce a better
  395. // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
  396. if (IsChkVariant) {
  397. FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
  398. FunctionName = FunctionName.drop_back(std::strlen("_chk"));
  399. } else if (FunctionName.startswith("__builtin_")) {
  400. FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
  401. }
  402. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  403. PDiag(DiagID)
  404. << FunctionName << ObjectSize.toString(/*Radix=*/10)
  405. << UsedSize.toString(/*Radix=*/10));
  406. }
  407. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  408. Scope::ScopeFlags NeededScopeFlags,
  409. unsigned DiagID) {
  410. // Scopes aren't available during instantiation. Fortunately, builtin
  411. // functions cannot be template args so they cannot be formed through template
  412. // instantiation. Therefore checking once during the parse is sufficient.
  413. if (SemaRef.inTemplateInstantiation())
  414. return false;
  415. Scope *S = SemaRef.getCurScope();
  416. while (S && !S->isSEHExceptScope())
  417. S = S->getParent();
  418. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  419. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  420. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  421. << DRE->getDecl()->getIdentifier();
  422. return true;
  423. }
  424. return false;
  425. }
  426. static inline bool isBlockPointer(Expr *Arg) {
  427. return Arg->getType()->isBlockPointerType();
  428. }
  429. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  430. /// void*, which is a requirement of device side enqueue.
  431. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  432. const BlockPointerType *BPT =
  433. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  434. ArrayRef<QualType> Params =
  435. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  436. unsigned ArgCounter = 0;
  437. bool IllegalParams = false;
  438. // Iterate through the block parameters until either one is found that is not
  439. // a local void*, or the block is valid.
  440. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  441. I != E; ++I, ++ArgCounter) {
  442. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  443. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  444. LangAS::opencl_local) {
  445. // Get the location of the error. If a block literal has been passed
  446. // (BlockExpr) then we can point straight to the offending argument,
  447. // else we just point to the variable reference.
  448. SourceLocation ErrorLoc;
  449. if (isa<BlockExpr>(BlockArg)) {
  450. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  451. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  452. } else if (isa<DeclRefExpr>(BlockArg)) {
  453. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  454. }
  455. S.Diag(ErrorLoc,
  456. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  457. IllegalParams = true;
  458. }
  459. }
  460. return IllegalParams;
  461. }
  462. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  463. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  464. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  465. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  466. return true;
  467. }
  468. return false;
  469. }
  470. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  471. if (checkArgCount(S, TheCall, 2))
  472. return true;
  473. if (checkOpenCLSubgroupExt(S, TheCall))
  474. return true;
  475. // First argument is an ndrange_t type.
  476. Expr *NDRangeArg = TheCall->getArg(0);
  477. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  478. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  479. << TheCall->getDirectCallee() << "'ndrange_t'";
  480. return true;
  481. }
  482. Expr *BlockArg = TheCall->getArg(1);
  483. if (!isBlockPointer(BlockArg)) {
  484. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  485. << TheCall->getDirectCallee() << "block";
  486. return true;
  487. }
  488. return checkOpenCLBlockArgs(S, BlockArg);
  489. }
  490. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  491. /// get_kernel_work_group_size
  492. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  493. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  494. if (checkArgCount(S, TheCall, 1))
  495. return true;
  496. Expr *BlockArg = TheCall->getArg(0);
  497. if (!isBlockPointer(BlockArg)) {
  498. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  499. << TheCall->getDirectCallee() << "block";
  500. return true;
  501. }
  502. return checkOpenCLBlockArgs(S, BlockArg);
  503. }
  504. /// Diagnose integer type and any valid implicit conversion to it.
  505. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  506. const QualType &IntType);
  507. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  508. unsigned Start, unsigned End) {
  509. bool IllegalParams = false;
  510. for (unsigned I = Start; I <= End; ++I)
  511. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  512. S.Context.getSizeType());
  513. return IllegalParams;
  514. }
  515. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  516. /// 'local void*' parameter of passed block.
  517. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  518. Expr *BlockArg,
  519. unsigned NumNonVarArgs) {
  520. const BlockPointerType *BPT =
  521. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  522. unsigned NumBlockParams =
  523. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  524. unsigned TotalNumArgs = TheCall->getNumArgs();
  525. // For each argument passed to the block, a corresponding uint needs to
  526. // be passed to describe the size of the local memory.
  527. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  528. S.Diag(TheCall->getBeginLoc(),
  529. diag::err_opencl_enqueue_kernel_local_size_args);
  530. return true;
  531. }
  532. // Check that the sizes of the local memory are specified by integers.
  533. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  534. TotalNumArgs - 1);
  535. }
  536. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  537. /// overload formats specified in Table 6.13.17.1.
  538. /// int enqueue_kernel(queue_t queue,
  539. /// kernel_enqueue_flags_t flags,
  540. /// const ndrange_t ndrange,
  541. /// void (^block)(void))
  542. /// int enqueue_kernel(queue_t queue,
  543. /// kernel_enqueue_flags_t flags,
  544. /// const ndrange_t ndrange,
  545. /// uint num_events_in_wait_list,
  546. /// clk_event_t *event_wait_list,
  547. /// clk_event_t *event_ret,
  548. /// void (^block)(void))
  549. /// int enqueue_kernel(queue_t queue,
  550. /// kernel_enqueue_flags_t flags,
  551. /// const ndrange_t ndrange,
  552. /// void (^block)(local void*, ...),
  553. /// uint size0, ...)
  554. /// int enqueue_kernel(queue_t queue,
  555. /// kernel_enqueue_flags_t flags,
  556. /// const ndrange_t ndrange,
  557. /// uint num_events_in_wait_list,
  558. /// clk_event_t *event_wait_list,
  559. /// clk_event_t *event_ret,
  560. /// void (^block)(local void*, ...),
  561. /// uint size0, ...)
  562. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  563. unsigned NumArgs = TheCall->getNumArgs();
  564. if (NumArgs < 4) {
  565. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  566. return true;
  567. }
  568. Expr *Arg0 = TheCall->getArg(0);
  569. Expr *Arg1 = TheCall->getArg(1);
  570. Expr *Arg2 = TheCall->getArg(2);
  571. Expr *Arg3 = TheCall->getArg(3);
  572. // First argument always needs to be a queue_t type.
  573. if (!Arg0->getType()->isQueueT()) {
  574. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  575. diag::err_opencl_builtin_expected_type)
  576. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  577. return true;
  578. }
  579. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  580. if (!Arg1->getType()->isIntegerType()) {
  581. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  582. diag::err_opencl_builtin_expected_type)
  583. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  584. return true;
  585. }
  586. // Third argument is always an ndrange_t type.
  587. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  588. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  589. diag::err_opencl_builtin_expected_type)
  590. << TheCall->getDirectCallee() << "'ndrange_t'";
  591. return true;
  592. }
  593. // With four arguments, there is only one form that the function could be
  594. // called in: no events and no variable arguments.
  595. if (NumArgs == 4) {
  596. // check that the last argument is the right block type.
  597. if (!isBlockPointer(Arg3)) {
  598. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  599. << TheCall->getDirectCallee() << "block";
  600. return true;
  601. }
  602. // we have a block type, check the prototype
  603. const BlockPointerType *BPT =
  604. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  605. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  606. S.Diag(Arg3->getBeginLoc(),
  607. diag::err_opencl_enqueue_kernel_blocks_no_args);
  608. return true;
  609. }
  610. return false;
  611. }
  612. // we can have block + varargs.
  613. if (isBlockPointer(Arg3))
  614. return (checkOpenCLBlockArgs(S, Arg3) ||
  615. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  616. // last two cases with either exactly 7 args or 7 args and varargs.
  617. if (NumArgs >= 7) {
  618. // check common block argument.
  619. Expr *Arg6 = TheCall->getArg(6);
  620. if (!isBlockPointer(Arg6)) {
  621. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  622. << TheCall->getDirectCallee() << "block";
  623. return true;
  624. }
  625. if (checkOpenCLBlockArgs(S, Arg6))
  626. return true;
  627. // Forth argument has to be any integer type.
  628. if (!Arg3->getType()->isIntegerType()) {
  629. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  630. diag::err_opencl_builtin_expected_type)
  631. << TheCall->getDirectCallee() << "integer";
  632. return true;
  633. }
  634. // check remaining common arguments.
  635. Expr *Arg4 = TheCall->getArg(4);
  636. Expr *Arg5 = TheCall->getArg(5);
  637. // Fifth argument is always passed as a pointer to clk_event_t.
  638. if (!Arg4->isNullPointerConstant(S.Context,
  639. Expr::NPC_ValueDependentIsNotNull) &&
  640. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  641. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  642. diag::err_opencl_builtin_expected_type)
  643. << TheCall->getDirectCallee()
  644. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  645. return true;
  646. }
  647. // Sixth argument is always passed as a pointer to clk_event_t.
  648. if (!Arg5->isNullPointerConstant(S.Context,
  649. Expr::NPC_ValueDependentIsNotNull) &&
  650. !(Arg5->getType()->isPointerType() &&
  651. Arg5->getType()->getPointeeType()->isClkEventT())) {
  652. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  653. diag::err_opencl_builtin_expected_type)
  654. << TheCall->getDirectCallee()
  655. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  656. return true;
  657. }
  658. if (NumArgs == 7)
  659. return false;
  660. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  661. }
  662. // None of the specific case has been detected, give generic error
  663. S.Diag(TheCall->getBeginLoc(),
  664. diag::err_opencl_enqueue_kernel_incorrect_args);
  665. return true;
  666. }
  667. /// Returns OpenCL access qual.
  668. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  669. return D->getAttr<OpenCLAccessAttr>();
  670. }
  671. /// Returns true if pipe element type is different from the pointer.
  672. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  673. const Expr *Arg0 = Call->getArg(0);
  674. // First argument type should always be pipe.
  675. if (!Arg0->getType()->isPipeType()) {
  676. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  677. << Call->getDirectCallee() << Arg0->getSourceRange();
  678. return true;
  679. }
  680. OpenCLAccessAttr *AccessQual =
  681. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  682. // Validates the access qualifier is compatible with the call.
  683. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  684. // read_only and write_only, and assumed to be read_only if no qualifier is
  685. // specified.
  686. switch (Call->getDirectCallee()->getBuiltinID()) {
  687. case Builtin::BIread_pipe:
  688. case Builtin::BIreserve_read_pipe:
  689. case Builtin::BIcommit_read_pipe:
  690. case Builtin::BIwork_group_reserve_read_pipe:
  691. case Builtin::BIsub_group_reserve_read_pipe:
  692. case Builtin::BIwork_group_commit_read_pipe:
  693. case Builtin::BIsub_group_commit_read_pipe:
  694. if (!(!AccessQual || AccessQual->isReadOnly())) {
  695. S.Diag(Arg0->getBeginLoc(),
  696. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  697. << "read_only" << Arg0->getSourceRange();
  698. return true;
  699. }
  700. break;
  701. case Builtin::BIwrite_pipe:
  702. case Builtin::BIreserve_write_pipe:
  703. case Builtin::BIcommit_write_pipe:
  704. case Builtin::BIwork_group_reserve_write_pipe:
  705. case Builtin::BIsub_group_reserve_write_pipe:
  706. case Builtin::BIwork_group_commit_write_pipe:
  707. case Builtin::BIsub_group_commit_write_pipe:
  708. if (!(AccessQual && AccessQual->isWriteOnly())) {
  709. S.Diag(Arg0->getBeginLoc(),
  710. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  711. << "write_only" << Arg0->getSourceRange();
  712. return true;
  713. }
  714. break;
  715. default:
  716. break;
  717. }
  718. return false;
  719. }
  720. /// Returns true if pipe element type is different from the pointer.
  721. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  722. const Expr *Arg0 = Call->getArg(0);
  723. const Expr *ArgIdx = Call->getArg(Idx);
  724. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  725. const QualType EltTy = PipeTy->getElementType();
  726. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  727. // The Idx argument should be a pointer and the type of the pointer and
  728. // the type of pipe element should also be the same.
  729. if (!ArgTy ||
  730. !S.Context.hasSameType(
  731. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  732. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  733. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  734. << ArgIdx->getType() << ArgIdx->getSourceRange();
  735. return true;
  736. }
  737. return false;
  738. }
  739. // Performs semantic analysis for the read/write_pipe call.
  740. // \param S Reference to the semantic analyzer.
  741. // \param Call A pointer to the builtin call.
  742. // \return True if a semantic error has been found, false otherwise.
  743. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  744. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  745. // functions have two forms.
  746. switch (Call->getNumArgs()) {
  747. case 2:
  748. if (checkOpenCLPipeArg(S, Call))
  749. return true;
  750. // The call with 2 arguments should be
  751. // read/write_pipe(pipe T, T*).
  752. // Check packet type T.
  753. if (checkOpenCLPipePacketType(S, Call, 1))
  754. return true;
  755. break;
  756. case 4: {
  757. if (checkOpenCLPipeArg(S, Call))
  758. return true;
  759. // The call with 4 arguments should be
  760. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  761. // Check reserve_id_t.
  762. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  763. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  764. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  765. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  766. return true;
  767. }
  768. // Check the index.
  769. const Expr *Arg2 = Call->getArg(2);
  770. if (!Arg2->getType()->isIntegerType() &&
  771. !Arg2->getType()->isUnsignedIntegerType()) {
  772. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  773. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  774. << Arg2->getType() << Arg2->getSourceRange();
  775. return true;
  776. }
  777. // Check packet type T.
  778. if (checkOpenCLPipePacketType(S, Call, 3))
  779. return true;
  780. } break;
  781. default:
  782. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  783. << Call->getDirectCallee() << Call->getSourceRange();
  784. return true;
  785. }
  786. return false;
  787. }
  788. // Performs a semantic analysis on the {work_group_/sub_group_
  789. // /_}reserve_{read/write}_pipe
  790. // \param S Reference to the semantic analyzer.
  791. // \param Call The call to the builtin function to be analyzed.
  792. // \return True if a semantic error was found, false otherwise.
  793. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  794. if (checkArgCount(S, Call, 2))
  795. return true;
  796. if (checkOpenCLPipeArg(S, Call))
  797. return true;
  798. // Check the reserve size.
  799. if (!Call->getArg(1)->getType()->isIntegerType() &&
  800. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  801. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  802. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  803. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  804. return true;
  805. }
  806. // Since return type of reserve_read/write_pipe built-in function is
  807. // reserve_id_t, which is not defined in the builtin def file , we used int
  808. // as return type and need to override the return type of these functions.
  809. Call->setType(S.Context.OCLReserveIDTy);
  810. return false;
  811. }
  812. // Performs a semantic analysis on {work_group_/sub_group_
  813. // /_}commit_{read/write}_pipe
  814. // \param S Reference to the semantic analyzer.
  815. // \param Call The call to the builtin function to be analyzed.
  816. // \return True if a semantic error was found, false otherwise.
  817. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  818. if (checkArgCount(S, Call, 2))
  819. return true;
  820. if (checkOpenCLPipeArg(S, Call))
  821. return true;
  822. // Check reserve_id_t.
  823. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  824. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  825. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  826. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  827. return true;
  828. }
  829. return false;
  830. }
  831. // Performs a semantic analysis on the call to built-in Pipe
  832. // Query Functions.
  833. // \param S Reference to the semantic analyzer.
  834. // \param Call The call to the builtin function to be analyzed.
  835. // \return True if a semantic error was found, false otherwise.
  836. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  837. if (checkArgCount(S, Call, 1))
  838. return true;
  839. if (!Call->getArg(0)->getType()->isPipeType()) {
  840. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  841. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  842. return true;
  843. }
  844. return false;
  845. }
  846. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  847. // Performs semantic analysis for the to_global/local/private call.
  848. // \param S Reference to the semantic analyzer.
  849. // \param BuiltinID ID of the builtin function.
  850. // \param Call A pointer to the builtin call.
  851. // \return True if a semantic error has been found, false otherwise.
  852. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  853. CallExpr *Call) {
  854. if (Call->getNumArgs() != 1) {
  855. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  856. << Call->getDirectCallee() << Call->getSourceRange();
  857. return true;
  858. }
  859. auto RT = Call->getArg(0)->getType();
  860. if (!RT->isPointerType() || RT->getPointeeType()
  861. .getAddressSpace() == LangAS::opencl_constant) {
  862. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  863. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  864. return true;
  865. }
  866. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  867. S.Diag(Call->getArg(0)->getBeginLoc(),
  868. diag::warn_opencl_generic_address_space_arg)
  869. << Call->getDirectCallee()->getNameInfo().getAsString()
  870. << Call->getArg(0)->getSourceRange();
  871. }
  872. RT = RT->getPointeeType();
  873. auto Qual = RT.getQualifiers();
  874. switch (BuiltinID) {
  875. case Builtin::BIto_global:
  876. Qual.setAddressSpace(LangAS::opencl_global);
  877. break;
  878. case Builtin::BIto_local:
  879. Qual.setAddressSpace(LangAS::opencl_local);
  880. break;
  881. case Builtin::BIto_private:
  882. Qual.setAddressSpace(LangAS::opencl_private);
  883. break;
  884. default:
  885. llvm_unreachable("Invalid builtin function");
  886. }
  887. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  888. RT.getUnqualifiedType(), Qual)));
  889. return false;
  890. }
  891. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  892. if (checkArgCount(S, TheCall, 1))
  893. return ExprError();
  894. // Compute __builtin_launder's parameter type from the argument.
  895. // The parameter type is:
  896. // * The type of the argument if it's not an array or function type,
  897. // Otherwise,
  898. // * The decayed argument type.
  899. QualType ParamTy = [&]() {
  900. QualType ArgTy = TheCall->getArg(0)->getType();
  901. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  902. return S.Context.getPointerType(Ty->getElementType());
  903. if (ArgTy->isFunctionType()) {
  904. return S.Context.getPointerType(ArgTy);
  905. }
  906. return ArgTy;
  907. }();
  908. TheCall->setType(ParamTy);
  909. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  910. if (!ParamTy->isPointerType())
  911. return 0;
  912. if (ParamTy->isFunctionPointerType())
  913. return 1;
  914. if (ParamTy->isVoidPointerType())
  915. return 2;
  916. return llvm::Optional<unsigned>{};
  917. }();
  918. if (DiagSelect.hasValue()) {
  919. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  920. << DiagSelect.getValue() << TheCall->getSourceRange();
  921. return ExprError();
  922. }
  923. // We either have an incomplete class type, or we have a class template
  924. // whose instantiation has not been forced. Example:
  925. //
  926. // template <class T> struct Foo { T value; };
  927. // Foo<int> *p = nullptr;
  928. // auto *d = __builtin_launder(p);
  929. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  930. diag::err_incomplete_type))
  931. return ExprError();
  932. assert(ParamTy->getPointeeType()->isObjectType() &&
  933. "Unhandled non-object pointer case");
  934. InitializedEntity Entity =
  935. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  936. ExprResult Arg =
  937. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  938. if (Arg.isInvalid())
  939. return ExprError();
  940. TheCall->setArg(0, Arg.get());
  941. return TheCall;
  942. }
  943. // Emit an error and return true if the current architecture is not in the list
  944. // of supported architectures.
  945. static bool
  946. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  947. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  948. llvm::Triple::ArchType CurArch =
  949. S.getASTContext().getTargetInfo().getTriple().getArch();
  950. if (llvm::is_contained(SupportedArchs, CurArch))
  951. return false;
  952. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  953. << TheCall->getSourceRange();
  954. return true;
  955. }
  956. ExprResult
  957. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  958. CallExpr *TheCall) {
  959. ExprResult TheCallResult(TheCall);
  960. // Find out if any arguments are required to be integer constant expressions.
  961. unsigned ICEArguments = 0;
  962. ASTContext::GetBuiltinTypeError Error;
  963. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  964. if (Error != ASTContext::GE_None)
  965. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  966. // If any arguments are required to be ICE's, check and diagnose.
  967. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  968. // Skip arguments not required to be ICE's.
  969. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  970. llvm::APSInt Result;
  971. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  972. return true;
  973. ICEArguments &= ~(1 << ArgNo);
  974. }
  975. switch (BuiltinID) {
  976. case Builtin::BI__builtin___CFStringMakeConstantString:
  977. assert(TheCall->getNumArgs() == 1 &&
  978. "Wrong # arguments to builtin CFStringMakeConstantString");
  979. if (CheckObjCString(TheCall->getArg(0)))
  980. return ExprError();
  981. break;
  982. case Builtin::BI__builtin_ms_va_start:
  983. case Builtin::BI__builtin_stdarg_start:
  984. case Builtin::BI__builtin_va_start:
  985. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  986. return ExprError();
  987. break;
  988. case Builtin::BI__va_start: {
  989. switch (Context.getTargetInfo().getTriple().getArch()) {
  990. case llvm::Triple::aarch64:
  991. case llvm::Triple::arm:
  992. case llvm::Triple::thumb:
  993. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  994. return ExprError();
  995. break;
  996. default:
  997. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  998. return ExprError();
  999. break;
  1000. }
  1001. break;
  1002. }
  1003. // The acquire, release, and no fence variants are ARM and AArch64 only.
  1004. case Builtin::BI_interlockedbittestandset_acq:
  1005. case Builtin::BI_interlockedbittestandset_rel:
  1006. case Builtin::BI_interlockedbittestandset_nf:
  1007. case Builtin::BI_interlockedbittestandreset_acq:
  1008. case Builtin::BI_interlockedbittestandreset_rel:
  1009. case Builtin::BI_interlockedbittestandreset_nf:
  1010. if (CheckBuiltinTargetSupport(
  1011. *this, BuiltinID, TheCall,
  1012. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  1013. return ExprError();
  1014. break;
  1015. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  1016. case Builtin::BI_bittest64:
  1017. case Builtin::BI_bittestandcomplement64:
  1018. case Builtin::BI_bittestandreset64:
  1019. case Builtin::BI_bittestandset64:
  1020. case Builtin::BI_interlockedbittestandreset64:
  1021. case Builtin::BI_interlockedbittestandset64:
  1022. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  1023. {llvm::Triple::x86_64, llvm::Triple::arm,
  1024. llvm::Triple::thumb, llvm::Triple::aarch64}))
  1025. return ExprError();
  1026. break;
  1027. case Builtin::BI__builtin_isgreater:
  1028. case Builtin::BI__builtin_isgreaterequal:
  1029. case Builtin::BI__builtin_isless:
  1030. case Builtin::BI__builtin_islessequal:
  1031. case Builtin::BI__builtin_islessgreater:
  1032. case Builtin::BI__builtin_isunordered:
  1033. if (SemaBuiltinUnorderedCompare(TheCall))
  1034. return ExprError();
  1035. break;
  1036. case Builtin::BI__builtin_fpclassify:
  1037. if (SemaBuiltinFPClassification(TheCall, 6))
  1038. return ExprError();
  1039. break;
  1040. case Builtin::BI__builtin_isfinite:
  1041. case Builtin::BI__builtin_isinf:
  1042. case Builtin::BI__builtin_isinf_sign:
  1043. case Builtin::BI__builtin_isnan:
  1044. case Builtin::BI__builtin_isnormal:
  1045. case Builtin::BI__builtin_signbit:
  1046. case Builtin::BI__builtin_signbitf:
  1047. case Builtin::BI__builtin_signbitl:
  1048. if (SemaBuiltinFPClassification(TheCall, 1))
  1049. return ExprError();
  1050. break;
  1051. case Builtin::BI__builtin_shufflevector:
  1052. return SemaBuiltinShuffleVector(TheCall);
  1053. // TheCall will be freed by the smart pointer here, but that's fine, since
  1054. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  1055. case Builtin::BI__builtin_prefetch:
  1056. if (SemaBuiltinPrefetch(TheCall))
  1057. return ExprError();
  1058. break;
  1059. case Builtin::BI__builtin_alloca_with_align:
  1060. if (SemaBuiltinAllocaWithAlign(TheCall))
  1061. return ExprError();
  1062. break;
  1063. case Builtin::BI__assume:
  1064. case Builtin::BI__builtin_assume:
  1065. if (SemaBuiltinAssume(TheCall))
  1066. return ExprError();
  1067. break;
  1068. case Builtin::BI__builtin_assume_aligned:
  1069. if (SemaBuiltinAssumeAligned(TheCall))
  1070. return ExprError();
  1071. break;
  1072. case Builtin::BI__builtin_dynamic_object_size:
  1073. case Builtin::BI__builtin_object_size:
  1074. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  1075. return ExprError();
  1076. break;
  1077. case Builtin::BI__builtin_longjmp:
  1078. if (SemaBuiltinLongjmp(TheCall))
  1079. return ExprError();
  1080. break;
  1081. case Builtin::BI__builtin_setjmp:
  1082. if (SemaBuiltinSetjmp(TheCall))
  1083. return ExprError();
  1084. break;
  1085. case Builtin::BI_setjmp:
  1086. case Builtin::BI_setjmpex:
  1087. if (checkArgCount(*this, TheCall, 1))
  1088. return true;
  1089. break;
  1090. case Builtin::BI__builtin_classify_type:
  1091. if (checkArgCount(*this, TheCall, 1)) return true;
  1092. TheCall->setType(Context.IntTy);
  1093. break;
  1094. case Builtin::BI__builtin_constant_p: {
  1095. if (checkArgCount(*this, TheCall, 1)) return true;
  1096. ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
  1097. if (Arg.isInvalid()) return true;
  1098. TheCall->setArg(0, Arg.get());
  1099. TheCall->setType(Context.IntTy);
  1100. break;
  1101. }
  1102. case Builtin::BI__builtin_launder:
  1103. return SemaBuiltinLaunder(*this, TheCall);
  1104. case Builtin::BI__sync_fetch_and_add:
  1105. case Builtin::BI__sync_fetch_and_add_1:
  1106. case Builtin::BI__sync_fetch_and_add_2:
  1107. case Builtin::BI__sync_fetch_and_add_4:
  1108. case Builtin::BI__sync_fetch_and_add_8:
  1109. case Builtin::BI__sync_fetch_and_add_16:
  1110. case Builtin::BI__sync_fetch_and_sub:
  1111. case Builtin::BI__sync_fetch_and_sub_1:
  1112. case Builtin::BI__sync_fetch_and_sub_2:
  1113. case Builtin::BI__sync_fetch_and_sub_4:
  1114. case Builtin::BI__sync_fetch_and_sub_8:
  1115. case Builtin::BI__sync_fetch_and_sub_16:
  1116. case Builtin::BI__sync_fetch_and_or:
  1117. case Builtin::BI__sync_fetch_and_or_1:
  1118. case Builtin::BI__sync_fetch_and_or_2:
  1119. case Builtin::BI__sync_fetch_and_or_4:
  1120. case Builtin::BI__sync_fetch_and_or_8:
  1121. case Builtin::BI__sync_fetch_and_or_16:
  1122. case Builtin::BI__sync_fetch_and_and:
  1123. case Builtin::BI__sync_fetch_and_and_1:
  1124. case Builtin::BI__sync_fetch_and_and_2:
  1125. case Builtin::BI__sync_fetch_and_and_4:
  1126. case Builtin::BI__sync_fetch_and_and_8:
  1127. case Builtin::BI__sync_fetch_and_and_16:
  1128. case Builtin::BI__sync_fetch_and_xor:
  1129. case Builtin::BI__sync_fetch_and_xor_1:
  1130. case Builtin::BI__sync_fetch_and_xor_2:
  1131. case Builtin::BI__sync_fetch_and_xor_4:
  1132. case Builtin::BI__sync_fetch_and_xor_8:
  1133. case Builtin::BI__sync_fetch_and_xor_16:
  1134. case Builtin::BI__sync_fetch_and_nand:
  1135. case Builtin::BI__sync_fetch_and_nand_1:
  1136. case Builtin::BI__sync_fetch_and_nand_2:
  1137. case Builtin::BI__sync_fetch_and_nand_4:
  1138. case Builtin::BI__sync_fetch_and_nand_8:
  1139. case Builtin::BI__sync_fetch_and_nand_16:
  1140. case Builtin::BI__sync_add_and_fetch:
  1141. case Builtin::BI__sync_add_and_fetch_1:
  1142. case Builtin::BI__sync_add_and_fetch_2:
  1143. case Builtin::BI__sync_add_and_fetch_4:
  1144. case Builtin::BI__sync_add_and_fetch_8:
  1145. case Builtin::BI__sync_add_and_fetch_16:
  1146. case Builtin::BI__sync_sub_and_fetch:
  1147. case Builtin::BI__sync_sub_and_fetch_1:
  1148. case Builtin::BI__sync_sub_and_fetch_2:
  1149. case Builtin::BI__sync_sub_and_fetch_4:
  1150. case Builtin::BI__sync_sub_and_fetch_8:
  1151. case Builtin::BI__sync_sub_and_fetch_16:
  1152. case Builtin::BI__sync_and_and_fetch:
  1153. case Builtin::BI__sync_and_and_fetch_1:
  1154. case Builtin::BI__sync_and_and_fetch_2:
  1155. case Builtin::BI__sync_and_and_fetch_4:
  1156. case Builtin::BI__sync_and_and_fetch_8:
  1157. case Builtin::BI__sync_and_and_fetch_16:
  1158. case Builtin::BI__sync_or_and_fetch:
  1159. case Builtin::BI__sync_or_and_fetch_1:
  1160. case Builtin::BI__sync_or_and_fetch_2:
  1161. case Builtin::BI__sync_or_and_fetch_4:
  1162. case Builtin::BI__sync_or_and_fetch_8:
  1163. case Builtin::BI__sync_or_and_fetch_16:
  1164. case Builtin::BI__sync_xor_and_fetch:
  1165. case Builtin::BI__sync_xor_and_fetch_1:
  1166. case Builtin::BI__sync_xor_and_fetch_2:
  1167. case Builtin::BI__sync_xor_and_fetch_4:
  1168. case Builtin::BI__sync_xor_and_fetch_8:
  1169. case Builtin::BI__sync_xor_and_fetch_16:
  1170. case Builtin::BI__sync_nand_and_fetch:
  1171. case Builtin::BI__sync_nand_and_fetch_1:
  1172. case Builtin::BI__sync_nand_and_fetch_2:
  1173. case Builtin::BI__sync_nand_and_fetch_4:
  1174. case Builtin::BI__sync_nand_and_fetch_8:
  1175. case Builtin::BI__sync_nand_and_fetch_16:
  1176. case Builtin::BI__sync_val_compare_and_swap:
  1177. case Builtin::BI__sync_val_compare_and_swap_1:
  1178. case Builtin::BI__sync_val_compare_and_swap_2:
  1179. case Builtin::BI__sync_val_compare_and_swap_4:
  1180. case Builtin::BI__sync_val_compare_and_swap_8:
  1181. case Builtin::BI__sync_val_compare_and_swap_16:
  1182. case Builtin::BI__sync_bool_compare_and_swap:
  1183. case Builtin::BI__sync_bool_compare_and_swap_1:
  1184. case Builtin::BI__sync_bool_compare_and_swap_2:
  1185. case Builtin::BI__sync_bool_compare_and_swap_4:
  1186. case Builtin::BI__sync_bool_compare_and_swap_8:
  1187. case Builtin::BI__sync_bool_compare_and_swap_16:
  1188. case Builtin::BI__sync_lock_test_and_set:
  1189. case Builtin::BI__sync_lock_test_and_set_1:
  1190. case Builtin::BI__sync_lock_test_and_set_2:
  1191. case Builtin::BI__sync_lock_test_and_set_4:
  1192. case Builtin::BI__sync_lock_test_and_set_8:
  1193. case Builtin::BI__sync_lock_test_and_set_16:
  1194. case Builtin::BI__sync_lock_release:
  1195. case Builtin::BI__sync_lock_release_1:
  1196. case Builtin::BI__sync_lock_release_2:
  1197. case Builtin::BI__sync_lock_release_4:
  1198. case Builtin::BI__sync_lock_release_8:
  1199. case Builtin::BI__sync_lock_release_16:
  1200. case Builtin::BI__sync_swap:
  1201. case Builtin::BI__sync_swap_1:
  1202. case Builtin::BI__sync_swap_2:
  1203. case Builtin::BI__sync_swap_4:
  1204. case Builtin::BI__sync_swap_8:
  1205. case Builtin::BI__sync_swap_16:
  1206. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1207. case Builtin::BI__sync_synchronize:
  1208. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1209. << TheCall->getCallee()->getSourceRange();
  1210. break;
  1211. case Builtin::BI__builtin_nontemporal_load:
  1212. case Builtin::BI__builtin_nontemporal_store:
  1213. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1214. #define BUILTIN(ID, TYPE, ATTRS)
  1215. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1216. case Builtin::BI##ID: \
  1217. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1218. #include "clang/Basic/Builtins.def"
  1219. case Builtin::BI__annotation:
  1220. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1221. return ExprError();
  1222. break;
  1223. case Builtin::BI__builtin_annotation:
  1224. if (SemaBuiltinAnnotation(*this, TheCall))
  1225. return ExprError();
  1226. break;
  1227. case Builtin::BI__builtin_addressof:
  1228. if (SemaBuiltinAddressof(*this, TheCall))
  1229. return ExprError();
  1230. break;
  1231. case Builtin::BI__builtin_add_overflow:
  1232. case Builtin::BI__builtin_sub_overflow:
  1233. case Builtin::BI__builtin_mul_overflow:
  1234. if (SemaBuiltinOverflow(*this, TheCall))
  1235. return ExprError();
  1236. break;
  1237. case Builtin::BI__builtin_operator_new:
  1238. case Builtin::BI__builtin_operator_delete: {
  1239. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1240. ExprResult Res =
  1241. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1242. if (Res.isInvalid())
  1243. CorrectDelayedTyposInExpr(TheCallResult.get());
  1244. return Res;
  1245. }
  1246. case Builtin::BI__builtin_dump_struct: {
  1247. // We first want to ensure we are called with 2 arguments
  1248. if (checkArgCount(*this, TheCall, 2))
  1249. return ExprError();
  1250. // Ensure that the first argument is of type 'struct XX *'
  1251. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1252. const QualType PtrArgType = PtrArg->getType();
  1253. if (!PtrArgType->isPointerType() ||
  1254. !PtrArgType->getPointeeType()->isRecordType()) {
  1255. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1256. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1257. << "structure pointer";
  1258. return ExprError();
  1259. }
  1260. // Ensure that the second argument is of type 'FunctionType'
  1261. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1262. const QualType FnPtrArgType = FnPtrArg->getType();
  1263. if (!FnPtrArgType->isPointerType()) {
  1264. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1265. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1266. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1267. return ExprError();
  1268. }
  1269. const auto *FuncType =
  1270. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1271. if (!FuncType) {
  1272. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1273. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1274. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1275. return ExprError();
  1276. }
  1277. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1278. if (!FT->getNumParams()) {
  1279. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1280. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1281. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1282. return ExprError();
  1283. }
  1284. QualType PT = FT->getParamType(0);
  1285. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1286. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1287. !PT->getPointeeType().isConstQualified()) {
  1288. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1289. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1290. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1291. return ExprError();
  1292. }
  1293. }
  1294. TheCall->setType(Context.IntTy);
  1295. break;
  1296. }
  1297. case Builtin::BI__builtin_preserve_access_index:
  1298. if (SemaBuiltinPreserveAI(*this, TheCall))
  1299. return ExprError();
  1300. break;
  1301. case Builtin::BI__builtin_call_with_static_chain:
  1302. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1303. return ExprError();
  1304. break;
  1305. case Builtin::BI__exception_code:
  1306. case Builtin::BI_exception_code:
  1307. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1308. diag::err_seh___except_block))
  1309. return ExprError();
  1310. break;
  1311. case Builtin::BI__exception_info:
  1312. case Builtin::BI_exception_info:
  1313. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1314. diag::err_seh___except_filter))
  1315. return ExprError();
  1316. break;
  1317. case Builtin::BI__GetExceptionInfo:
  1318. if (checkArgCount(*this, TheCall, 1))
  1319. return ExprError();
  1320. if (CheckCXXThrowOperand(
  1321. TheCall->getBeginLoc(),
  1322. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1323. TheCall))
  1324. return ExprError();
  1325. TheCall->setType(Context.VoidPtrTy);
  1326. break;
  1327. // OpenCL v2.0, s6.13.16 - Pipe functions
  1328. case Builtin::BIread_pipe:
  1329. case Builtin::BIwrite_pipe:
  1330. // Since those two functions are declared with var args, we need a semantic
  1331. // check for the argument.
  1332. if (SemaBuiltinRWPipe(*this, TheCall))
  1333. return ExprError();
  1334. break;
  1335. case Builtin::BIreserve_read_pipe:
  1336. case Builtin::BIreserve_write_pipe:
  1337. case Builtin::BIwork_group_reserve_read_pipe:
  1338. case Builtin::BIwork_group_reserve_write_pipe:
  1339. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1340. return ExprError();
  1341. break;
  1342. case Builtin::BIsub_group_reserve_read_pipe:
  1343. case Builtin::BIsub_group_reserve_write_pipe:
  1344. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1345. SemaBuiltinReserveRWPipe(*this, TheCall))
  1346. return ExprError();
  1347. break;
  1348. case Builtin::BIcommit_read_pipe:
  1349. case Builtin::BIcommit_write_pipe:
  1350. case Builtin::BIwork_group_commit_read_pipe:
  1351. case Builtin::BIwork_group_commit_write_pipe:
  1352. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1353. return ExprError();
  1354. break;
  1355. case Builtin::BIsub_group_commit_read_pipe:
  1356. case Builtin::BIsub_group_commit_write_pipe:
  1357. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1358. SemaBuiltinCommitRWPipe(*this, TheCall))
  1359. return ExprError();
  1360. break;
  1361. case Builtin::BIget_pipe_num_packets:
  1362. case Builtin::BIget_pipe_max_packets:
  1363. if (SemaBuiltinPipePackets(*this, TheCall))
  1364. return ExprError();
  1365. break;
  1366. case Builtin::BIto_global:
  1367. case Builtin::BIto_local:
  1368. case Builtin::BIto_private:
  1369. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1370. return ExprError();
  1371. break;
  1372. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1373. case Builtin::BIenqueue_kernel:
  1374. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1375. return ExprError();
  1376. break;
  1377. case Builtin::BIget_kernel_work_group_size:
  1378. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1379. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1380. return ExprError();
  1381. break;
  1382. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1383. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1384. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1385. return ExprError();
  1386. break;
  1387. case Builtin::BI__builtin_os_log_format:
  1388. case Builtin::BI__builtin_os_log_format_buffer_size:
  1389. if (SemaBuiltinOSLogFormat(TheCall))
  1390. return ExprError();
  1391. break;
  1392. }
  1393. // Since the target specific builtins for each arch overlap, only check those
  1394. // of the arch we are compiling for.
  1395. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1396. switch (Context.getTargetInfo().getTriple().getArch()) {
  1397. case llvm::Triple::arm:
  1398. case llvm::Triple::armeb:
  1399. case llvm::Triple::thumb:
  1400. case llvm::Triple::thumbeb:
  1401. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1402. return ExprError();
  1403. break;
  1404. case llvm::Triple::aarch64:
  1405. case llvm::Triple::aarch64_be:
  1406. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1407. return ExprError();
  1408. break;
  1409. case llvm::Triple::hexagon:
  1410. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1411. return ExprError();
  1412. break;
  1413. case llvm::Triple::mips:
  1414. case llvm::Triple::mipsel:
  1415. case llvm::Triple::mips64:
  1416. case llvm::Triple::mips64el:
  1417. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1418. return ExprError();
  1419. break;
  1420. case llvm::Triple::systemz:
  1421. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1422. return ExprError();
  1423. break;
  1424. case llvm::Triple::x86:
  1425. case llvm::Triple::x86_64:
  1426. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1427. return ExprError();
  1428. break;
  1429. case llvm::Triple::ppc:
  1430. case llvm::Triple::ppc64:
  1431. case llvm::Triple::ppc64le:
  1432. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1433. return ExprError();
  1434. break;
  1435. default:
  1436. break;
  1437. }
  1438. }
  1439. return TheCallResult;
  1440. }
  1441. // Get the valid immediate range for the specified NEON type code.
  1442. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1443. NeonTypeFlags Type(t);
  1444. int IsQuad = ForceQuad ? true : Type.isQuad();
  1445. switch (Type.getEltType()) {
  1446. case NeonTypeFlags::Int8:
  1447. case NeonTypeFlags::Poly8:
  1448. return shift ? 7 : (8 << IsQuad) - 1;
  1449. case NeonTypeFlags::Int16:
  1450. case NeonTypeFlags::Poly16:
  1451. return shift ? 15 : (4 << IsQuad) - 1;
  1452. case NeonTypeFlags::Int32:
  1453. return shift ? 31 : (2 << IsQuad) - 1;
  1454. case NeonTypeFlags::Int64:
  1455. case NeonTypeFlags::Poly64:
  1456. return shift ? 63 : (1 << IsQuad) - 1;
  1457. case NeonTypeFlags::Poly128:
  1458. return shift ? 127 : (1 << IsQuad) - 1;
  1459. case NeonTypeFlags::Float16:
  1460. assert(!shift && "cannot shift float types!");
  1461. return (4 << IsQuad) - 1;
  1462. case NeonTypeFlags::Float32:
  1463. assert(!shift && "cannot shift float types!");
  1464. return (2 << IsQuad) - 1;
  1465. case NeonTypeFlags::Float64:
  1466. assert(!shift && "cannot shift float types!");
  1467. return (1 << IsQuad) - 1;
  1468. }
  1469. llvm_unreachable("Invalid NeonTypeFlag!");
  1470. }
  1471. /// getNeonEltType - Return the QualType corresponding to the elements of
  1472. /// the vector type specified by the NeonTypeFlags. This is used to check
  1473. /// the pointer arguments for Neon load/store intrinsics.
  1474. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1475. bool IsPolyUnsigned, bool IsInt64Long) {
  1476. switch (Flags.getEltType()) {
  1477. case NeonTypeFlags::Int8:
  1478. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1479. case NeonTypeFlags::Int16:
  1480. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1481. case NeonTypeFlags::Int32:
  1482. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1483. case NeonTypeFlags::Int64:
  1484. if (IsInt64Long)
  1485. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1486. else
  1487. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1488. : Context.LongLongTy;
  1489. case NeonTypeFlags::Poly8:
  1490. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1491. case NeonTypeFlags::Poly16:
  1492. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1493. case NeonTypeFlags::Poly64:
  1494. if (IsInt64Long)
  1495. return Context.UnsignedLongTy;
  1496. else
  1497. return Context.UnsignedLongLongTy;
  1498. case NeonTypeFlags::Poly128:
  1499. break;
  1500. case NeonTypeFlags::Float16:
  1501. return Context.HalfTy;
  1502. case NeonTypeFlags::Float32:
  1503. return Context.FloatTy;
  1504. case NeonTypeFlags::Float64:
  1505. return Context.DoubleTy;
  1506. }
  1507. llvm_unreachable("Invalid NeonTypeFlag!");
  1508. }
  1509. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1510. llvm::APSInt Result;
  1511. uint64_t mask = 0;
  1512. unsigned TV = 0;
  1513. int PtrArgNum = -1;
  1514. bool HasConstPtr = false;
  1515. switch (BuiltinID) {
  1516. #define GET_NEON_OVERLOAD_CHECK
  1517. #include "clang/Basic/arm_neon.inc"
  1518. #include "clang/Basic/arm_fp16.inc"
  1519. #undef GET_NEON_OVERLOAD_CHECK
  1520. }
  1521. // For NEON intrinsics which are overloaded on vector element type, validate
  1522. // the immediate which specifies which variant to emit.
  1523. unsigned ImmArg = TheCall->getNumArgs()-1;
  1524. if (mask) {
  1525. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1526. return true;
  1527. TV = Result.getLimitedValue(64);
  1528. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1529. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1530. << TheCall->getArg(ImmArg)->getSourceRange();
  1531. }
  1532. if (PtrArgNum >= 0) {
  1533. // Check that pointer arguments have the specified type.
  1534. Expr *Arg = TheCall->getArg(PtrArgNum);
  1535. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1536. Arg = ICE->getSubExpr();
  1537. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1538. QualType RHSTy = RHS.get()->getType();
  1539. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1540. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1541. Arch == llvm::Triple::aarch64_be;
  1542. bool IsInt64Long =
  1543. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1544. QualType EltTy =
  1545. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1546. if (HasConstPtr)
  1547. EltTy = EltTy.withConst();
  1548. QualType LHSTy = Context.getPointerType(EltTy);
  1549. AssignConvertType ConvTy;
  1550. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1551. if (RHS.isInvalid())
  1552. return true;
  1553. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1554. RHS.get(), AA_Assigning))
  1555. return true;
  1556. }
  1557. // For NEON intrinsics which take an immediate value as part of the
  1558. // instruction, range check them here.
  1559. unsigned i = 0, l = 0, u = 0;
  1560. switch (BuiltinID) {
  1561. default:
  1562. return false;
  1563. #define GET_NEON_IMMEDIATE_CHECK
  1564. #include "clang/Basic/arm_neon.inc"
  1565. #include "clang/Basic/arm_fp16.inc"
  1566. #undef GET_NEON_IMMEDIATE_CHECK
  1567. }
  1568. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1569. }
  1570. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1571. unsigned MaxWidth) {
  1572. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1573. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1574. BuiltinID == ARM::BI__builtin_arm_strex ||
  1575. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1576. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1577. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1578. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1579. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1580. "unexpected ARM builtin");
  1581. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1582. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1583. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1584. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1585. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1586. // Ensure that we have the proper number of arguments.
  1587. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1588. return true;
  1589. // Inspect the pointer argument of the atomic builtin. This should always be
  1590. // a pointer type, whose element is an integral scalar or pointer type.
  1591. // Because it is a pointer type, we don't have to worry about any implicit
  1592. // casts here.
  1593. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1594. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1595. if (PointerArgRes.isInvalid())
  1596. return true;
  1597. PointerArg = PointerArgRes.get();
  1598. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1599. if (!pointerType) {
  1600. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1601. << PointerArg->getType() << PointerArg->getSourceRange();
  1602. return true;
  1603. }
  1604. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1605. // task is to insert the appropriate casts into the AST. First work out just
  1606. // what the appropriate type is.
  1607. QualType ValType = pointerType->getPointeeType();
  1608. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1609. if (IsLdrex)
  1610. AddrType.addConst();
  1611. // Issue a warning if the cast is dodgy.
  1612. CastKind CastNeeded = CK_NoOp;
  1613. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1614. CastNeeded = CK_BitCast;
  1615. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1616. << PointerArg->getType() << Context.getPointerType(AddrType)
  1617. << AA_Passing << PointerArg->getSourceRange();
  1618. }
  1619. // Finally, do the cast and replace the argument with the corrected version.
  1620. AddrType = Context.getPointerType(AddrType);
  1621. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1622. if (PointerArgRes.isInvalid())
  1623. return true;
  1624. PointerArg = PointerArgRes.get();
  1625. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1626. // In general, we allow ints, floats and pointers to be loaded and stored.
  1627. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1628. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1629. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1630. << PointerArg->getType() << PointerArg->getSourceRange();
  1631. return true;
  1632. }
  1633. // But ARM doesn't have instructions to deal with 128-bit versions.
  1634. if (Context.getTypeSize(ValType) > MaxWidth) {
  1635. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1636. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1637. << PointerArg->getType() << PointerArg->getSourceRange();
  1638. return true;
  1639. }
  1640. switch (ValType.getObjCLifetime()) {
  1641. case Qualifiers::OCL_None:
  1642. case Qualifiers::OCL_ExplicitNone:
  1643. // okay
  1644. break;
  1645. case Qualifiers::OCL_Weak:
  1646. case Qualifiers::OCL_Strong:
  1647. case Qualifiers::OCL_Autoreleasing:
  1648. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1649. << ValType << PointerArg->getSourceRange();
  1650. return true;
  1651. }
  1652. if (IsLdrex) {
  1653. TheCall->setType(ValType);
  1654. return false;
  1655. }
  1656. // Initialize the argument to be stored.
  1657. ExprResult ValArg = TheCall->getArg(0);
  1658. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1659. Context, ValType, /*consume*/ false);
  1660. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1661. if (ValArg.isInvalid())
  1662. return true;
  1663. TheCall->setArg(0, ValArg.get());
  1664. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1665. // but the custom checker bypasses all default analysis.
  1666. TheCall->setType(Context.IntTy);
  1667. return false;
  1668. }
  1669. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1670. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1671. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1672. BuiltinID == ARM::BI__builtin_arm_strex ||
  1673. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1674. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1675. }
  1676. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1677. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1678. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1679. }
  1680. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1681. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1682. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1683. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1684. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1685. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1686. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1687. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1688. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1689. return true;
  1690. // For intrinsics which take an immediate value as part of the instruction,
  1691. // range check them here.
  1692. // FIXME: VFP Intrinsics should error if VFP not present.
  1693. switch (BuiltinID) {
  1694. default: return false;
  1695. case ARM::BI__builtin_arm_ssat:
  1696. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1697. case ARM::BI__builtin_arm_usat:
  1698. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1699. case ARM::BI__builtin_arm_ssat16:
  1700. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1701. case ARM::BI__builtin_arm_usat16:
  1702. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1703. case ARM::BI__builtin_arm_vcvtr_f:
  1704. case ARM::BI__builtin_arm_vcvtr_d:
  1705. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1706. case ARM::BI__builtin_arm_dmb:
  1707. case ARM::BI__builtin_arm_dsb:
  1708. case ARM::BI__builtin_arm_isb:
  1709. case ARM::BI__builtin_arm_dbg:
  1710. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1711. }
  1712. }
  1713. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1714. CallExpr *TheCall) {
  1715. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1716. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1717. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1718. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1719. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1720. }
  1721. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1722. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1723. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1724. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1725. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1726. }
  1727. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1728. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1729. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1730. // Memory Tagging Extensions (MTE) Intrinsics
  1731. if (BuiltinID == AArch64::BI__builtin_arm_irg ||
  1732. BuiltinID == AArch64::BI__builtin_arm_addg ||
  1733. BuiltinID == AArch64::BI__builtin_arm_gmi ||
  1734. BuiltinID == AArch64::BI__builtin_arm_ldg ||
  1735. BuiltinID == AArch64::BI__builtin_arm_stg ||
  1736. BuiltinID == AArch64::BI__builtin_arm_subp) {
  1737. return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
  1738. }
  1739. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1740. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1741. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1742. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1743. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1744. // Only check the valid encoding range. Any constant in this range would be
  1745. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1746. // an exception for incorrect registers. This matches MSVC behavior.
  1747. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1748. BuiltinID == AArch64::BI_WriteStatusReg)
  1749. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1750. if (BuiltinID == AArch64::BI__getReg)
  1751. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1752. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1753. return true;
  1754. // For intrinsics which take an immediate value as part of the instruction,
  1755. // range check them here.
  1756. unsigned i = 0, l = 0, u = 0;
  1757. switch (BuiltinID) {
  1758. default: return false;
  1759. case AArch64::BI__builtin_arm_dmb:
  1760. case AArch64::BI__builtin_arm_dsb:
  1761. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1762. }
  1763. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1764. }
  1765. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1766. struct BuiltinAndString {
  1767. unsigned BuiltinID;
  1768. const char *Str;
  1769. };
  1770. static BuiltinAndString ValidCPU[] = {
  1771. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1772. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1773. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1774. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1775. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1776. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1777. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1778. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1780. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1781. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1782. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1783. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1784. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1794. };
  1795. static BuiltinAndString ValidHVX[] = {
  1796. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2440. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2441. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2442. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2443. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2444. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2445. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2446. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2447. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2448. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2449. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2450. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2451. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2452. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2453. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2454. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2455. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2456. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2457. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2458. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2459. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2460. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2461. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2462. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2463. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2464. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2465. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2466. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2467. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2468. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2469. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2470. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2471. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2472. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2473. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2474. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2475. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2476. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2477. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2478. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2479. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2480. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2481. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2482. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2483. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2484. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2485. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2486. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2487. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2488. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2489. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2490. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2491. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2492. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2493. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2494. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2495. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2496. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2497. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2498. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2499. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2500. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2501. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2502. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2503. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2504. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2505. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2506. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2507. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2508. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2509. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2510. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2511. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2512. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2513. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2514. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2515. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2516. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2517. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2518. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2519. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2520. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2521. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2522. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2523. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2524. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2525. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2526. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2527. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2528. };
  2529. // Sort the tables on first execution so we can binary search them.
  2530. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2531. return LHS.BuiltinID < RHS.BuiltinID;
  2532. };
  2533. static const bool SortOnce =
  2534. (llvm::sort(ValidCPU, SortCmp),
  2535. llvm::sort(ValidHVX, SortCmp), true);
  2536. (void)SortOnce;
  2537. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2538. return BI.BuiltinID < BuiltinID;
  2539. };
  2540. const TargetInfo &TI = Context.getTargetInfo();
  2541. const BuiltinAndString *FC =
  2542. llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
  2543. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2544. const TargetOptions &Opts = TI.getTargetOpts();
  2545. StringRef CPU = Opts.CPU;
  2546. if (!CPU.empty()) {
  2547. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2548. CPU.consume_front("hexagon");
  2549. SmallVector<StringRef, 3> CPUs;
  2550. StringRef(FC->Str).split(CPUs, ',');
  2551. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2552. return Diag(TheCall->getBeginLoc(),
  2553. diag::err_hexagon_builtin_unsupported_cpu);
  2554. }
  2555. }
  2556. const BuiltinAndString *FH =
  2557. llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
  2558. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2559. if (!TI.hasFeature("hvx"))
  2560. return Diag(TheCall->getBeginLoc(),
  2561. diag::err_hexagon_builtin_requires_hvx);
  2562. SmallVector<StringRef, 3> HVXs;
  2563. StringRef(FH->Str).split(HVXs, ',');
  2564. bool IsValid = llvm::any_of(HVXs,
  2565. [&TI] (StringRef V) {
  2566. std::string F = "hvx" + V.str();
  2567. return TI.hasFeature(F);
  2568. });
  2569. if (!IsValid)
  2570. return Diag(TheCall->getBeginLoc(),
  2571. diag::err_hexagon_builtin_unsupported_hvx);
  2572. }
  2573. return false;
  2574. }
  2575. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2576. struct ArgInfo {
  2577. uint8_t OpNum;
  2578. bool IsSigned;
  2579. uint8_t BitWidth;
  2580. uint8_t Align;
  2581. };
  2582. struct BuiltinInfo {
  2583. unsigned BuiltinID;
  2584. ArgInfo Infos[2];
  2585. };
  2586. static BuiltinInfo Infos[] = {
  2587. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2588. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2589. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2590. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2591. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2592. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2593. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2594. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2595. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2596. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2597. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2598. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2599. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2600. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2601. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2602. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2603. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2604. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2609. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2613. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2614. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2615. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2616. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2617. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2618. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2619. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2620. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2621. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2622. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2623. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2624. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2625. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2626. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2627. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2628. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2629. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2630. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2631. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2632. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2633. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2634. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2635. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2636. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2637. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2638. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2647. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2649. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2650. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2657. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2661. {{ 1, false, 6, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2664. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2666. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2668. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2669. {{ 1, false, 5, 0 }} },
  2670. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2671. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2674. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2676. { 2, false, 5, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2678. { 2, false, 6, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2680. { 3, false, 5, 0 }} },
  2681. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2682. { 3, false, 6, 0 }} },
  2683. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2684. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2685. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2686. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2687. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2688. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2689. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2690. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2691. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2692. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2693. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2694. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2695. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2696. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2697. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2698. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2699. {{ 2, false, 4, 0 },
  2700. { 3, false, 5, 0 }} },
  2701. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2702. {{ 2, false, 4, 0 },
  2703. { 3, false, 5, 0 }} },
  2704. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2705. {{ 2, false, 4, 0 },
  2706. { 3, false, 5, 0 }} },
  2707. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2708. {{ 2, false, 4, 0 },
  2709. { 3, false, 5, 0 }} },
  2710. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2711. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2712. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2713. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2714. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2715. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2716. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2717. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2718. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2719. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2720. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2721. { 2, false, 5, 0 }} },
  2722. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2723. { 2, false, 6, 0 }} },
  2724. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2725. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2726. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2727. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2728. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2729. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2730. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2731. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2732. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2733. {{ 1, false, 4, 0 }} },
  2734. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2735. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2736. {{ 1, false, 4, 0 }} },
  2737. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2738. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2739. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2740. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2741. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2742. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2743. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2744. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2745. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2746. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2747. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2748. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2749. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2750. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2751. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2752. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2753. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2754. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2755. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2756. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2757. {{ 3, false, 1, 0 }} },
  2758. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2759. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2760. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2761. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2762. {{ 3, false, 1, 0 }} },
  2763. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2764. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2765. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2766. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2767. {{ 3, false, 1, 0 }} },
  2768. };
  2769. // Use a dynamically initialized static to sort the table exactly once on
  2770. // first run.
  2771. static const bool SortOnce =
  2772. (llvm::sort(Infos,
  2773. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2774. return LHS.BuiltinID < RHS.BuiltinID;
  2775. }),
  2776. true);
  2777. (void)SortOnce;
  2778. const BuiltinInfo *F = llvm::partition_point(
  2779. Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
  2780. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2781. return false;
  2782. bool Error = false;
  2783. for (const ArgInfo &A : F->Infos) {
  2784. // Ignore empty ArgInfo elements.
  2785. if (A.BitWidth == 0)
  2786. continue;
  2787. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2788. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2789. if (!A.Align) {
  2790. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2791. } else {
  2792. unsigned M = 1 << A.Align;
  2793. Min *= M;
  2794. Max *= M;
  2795. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2796. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2797. }
  2798. }
  2799. return Error;
  2800. }
  2801. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2802. CallExpr *TheCall) {
  2803. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2804. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2805. }
  2806. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2807. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2808. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2809. // by the underlying instruction i.e., df/m, df/n and then by size.
  2810. //
  2811. // FIXME: The size tests here should instead be tablegen'd along with the
  2812. // definitions from include/clang/Basic/BuiltinsMips.def.
  2813. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2814. // be too.
  2815. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2816. unsigned i = 0, l = 0, u = 0, m = 0;
  2817. switch (BuiltinID) {
  2818. default: return false;
  2819. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2820. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2821. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2822. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2823. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2824. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2825. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2826. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2827. // df/m field.
  2828. // These intrinsics take an unsigned 3 bit immediate.
  2829. case Mips::BI__builtin_msa_bclri_b:
  2830. case Mips::BI__builtin_msa_bnegi_b:
  2831. case Mips::BI__builtin_msa_bseti_b:
  2832. case Mips::BI__builtin_msa_sat_s_b:
  2833. case Mips::BI__builtin_msa_sat_u_b:
  2834. case Mips::BI__builtin_msa_slli_b:
  2835. case Mips::BI__builtin_msa_srai_b:
  2836. case Mips::BI__builtin_msa_srari_b:
  2837. case Mips::BI__builtin_msa_srli_b:
  2838. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2839. case Mips::BI__builtin_msa_binsli_b:
  2840. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2841. // These intrinsics take an unsigned 4 bit immediate.
  2842. case Mips::BI__builtin_msa_bclri_h:
  2843. case Mips::BI__builtin_msa_bnegi_h:
  2844. case Mips::BI__builtin_msa_bseti_h:
  2845. case Mips::BI__builtin_msa_sat_s_h:
  2846. case Mips::BI__builtin_msa_sat_u_h:
  2847. case Mips::BI__builtin_msa_slli_h:
  2848. case Mips::BI__builtin_msa_srai_h:
  2849. case Mips::BI__builtin_msa_srari_h:
  2850. case Mips::BI__builtin_msa_srli_h:
  2851. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2852. case Mips::BI__builtin_msa_binsli_h:
  2853. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2854. // These intrinsics take an unsigned 5 bit immediate.
  2855. // The first block of intrinsics actually have an unsigned 5 bit field,
  2856. // not a df/n field.
  2857. case Mips::BI__builtin_msa_cfcmsa:
  2858. case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
  2859. case Mips::BI__builtin_msa_clei_u_b:
  2860. case Mips::BI__builtin_msa_clei_u_h:
  2861. case Mips::BI__builtin_msa_clei_u_w:
  2862. case Mips::BI__builtin_msa_clei_u_d:
  2863. case Mips::BI__builtin_msa_clti_u_b:
  2864. case Mips::BI__builtin_msa_clti_u_h:
  2865. case Mips::BI__builtin_msa_clti_u_w:
  2866. case Mips::BI__builtin_msa_clti_u_d:
  2867. case Mips::BI__builtin_msa_maxi_u_b:
  2868. case Mips::BI__builtin_msa_maxi_u_h:
  2869. case Mips::BI__builtin_msa_maxi_u_w:
  2870. case Mips::BI__builtin_msa_maxi_u_d:
  2871. case Mips::BI__builtin_msa_mini_u_b:
  2872. case Mips::BI__builtin_msa_mini_u_h:
  2873. case Mips::BI__builtin_msa_mini_u_w:
  2874. case Mips::BI__builtin_msa_mini_u_d:
  2875. case Mips::BI__builtin_msa_addvi_b:
  2876. case Mips::BI__builtin_msa_addvi_h:
  2877. case Mips::BI__builtin_msa_addvi_w:
  2878. case Mips::BI__builtin_msa_addvi_d:
  2879. case Mips::BI__builtin_msa_bclri_w:
  2880. case Mips::BI__builtin_msa_bnegi_w:
  2881. case Mips::BI__builtin_msa_bseti_w:
  2882. case Mips::BI__builtin_msa_sat_s_w:
  2883. case Mips::BI__builtin_msa_sat_u_w:
  2884. case Mips::BI__builtin_msa_slli_w:
  2885. case Mips::BI__builtin_msa_srai_w:
  2886. case Mips::BI__builtin_msa_srari_w:
  2887. case Mips::BI__builtin_msa_srli_w:
  2888. case Mips::BI__builtin_msa_srlri_w:
  2889. case Mips::BI__builtin_msa_subvi_b:
  2890. case Mips::BI__builtin_msa_subvi_h:
  2891. case Mips::BI__builtin_msa_subvi_w:
  2892. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2893. case Mips::BI__builtin_msa_binsli_w:
  2894. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2895. // These intrinsics take an unsigned 6 bit immediate.
  2896. case Mips::BI__builtin_msa_bclri_d:
  2897. case Mips::BI__builtin_msa_bnegi_d:
  2898. case Mips::BI__builtin_msa_bseti_d:
  2899. case Mips::BI__builtin_msa_sat_s_d:
  2900. case Mips::BI__builtin_msa_sat_u_d:
  2901. case Mips::BI__builtin_msa_slli_d:
  2902. case Mips::BI__builtin_msa_srai_d:
  2903. case Mips::BI__builtin_msa_srari_d:
  2904. case Mips::BI__builtin_msa_srli_d:
  2905. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2906. case Mips::BI__builtin_msa_binsli_d:
  2907. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2908. // These intrinsics take a signed 5 bit immediate.
  2909. case Mips::BI__builtin_msa_ceqi_b:
  2910. case Mips::BI__builtin_msa_ceqi_h:
  2911. case Mips::BI__builtin_msa_ceqi_w:
  2912. case Mips::BI__builtin_msa_ceqi_d:
  2913. case Mips::BI__builtin_msa_clti_s_b:
  2914. case Mips::BI__builtin_msa_clti_s_h:
  2915. case Mips::BI__builtin_msa_clti_s_w:
  2916. case Mips::BI__builtin_msa_clti_s_d:
  2917. case Mips::BI__builtin_msa_clei_s_b:
  2918. case Mips::BI__builtin_msa_clei_s_h:
  2919. case Mips::BI__builtin_msa_clei_s_w:
  2920. case Mips::BI__builtin_msa_clei_s_d:
  2921. case Mips::BI__builtin_msa_maxi_s_b:
  2922. case Mips::BI__builtin_msa_maxi_s_h:
  2923. case Mips::BI__builtin_msa_maxi_s_w:
  2924. case Mips::BI__builtin_msa_maxi_s_d:
  2925. case Mips::BI__builtin_msa_mini_s_b:
  2926. case Mips::BI__builtin_msa_mini_s_h:
  2927. case Mips::BI__builtin_msa_mini_s_w:
  2928. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2929. // These intrinsics take an unsigned 8 bit immediate.
  2930. case Mips::BI__builtin_msa_andi_b:
  2931. case Mips::BI__builtin_msa_nori_b:
  2932. case Mips::BI__builtin_msa_ori_b:
  2933. case Mips::BI__builtin_msa_shf_b:
  2934. case Mips::BI__builtin_msa_shf_h:
  2935. case Mips::BI__builtin_msa_shf_w:
  2936. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2937. case Mips::BI__builtin_msa_bseli_b:
  2938. case Mips::BI__builtin_msa_bmnzi_b:
  2939. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2940. // df/n format
  2941. // These intrinsics take an unsigned 4 bit immediate.
  2942. case Mips::BI__builtin_msa_copy_s_b:
  2943. case Mips::BI__builtin_msa_copy_u_b:
  2944. case Mips::BI__builtin_msa_insve_b:
  2945. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2946. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2947. // These intrinsics take an unsigned 3 bit immediate.
  2948. case Mips::BI__builtin_msa_copy_s_h:
  2949. case Mips::BI__builtin_msa_copy_u_h:
  2950. case Mips::BI__builtin_msa_insve_h:
  2951. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2952. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2953. // These intrinsics take an unsigned 2 bit immediate.
  2954. case Mips::BI__builtin_msa_copy_s_w:
  2955. case Mips::BI__builtin_msa_copy_u_w:
  2956. case Mips::BI__builtin_msa_insve_w:
  2957. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2958. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2959. // These intrinsics take an unsigned 1 bit immediate.
  2960. case Mips::BI__builtin_msa_copy_s_d:
  2961. case Mips::BI__builtin_msa_copy_u_d:
  2962. case Mips::BI__builtin_msa_insve_d:
  2963. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2964. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2965. // Memory offsets and immediate loads.
  2966. // These intrinsics take a signed 10 bit immediate.
  2967. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2968. case Mips::BI__builtin_msa_ldi_h:
  2969. case Mips::BI__builtin_msa_ldi_w:
  2970. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2971. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2972. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2973. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2974. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2975. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2976. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2977. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2978. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2979. }
  2980. if (!m)
  2981. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2982. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2983. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2984. }
  2985. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2986. unsigned i = 0, l = 0, u = 0;
  2987. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2988. BuiltinID == PPC::BI__builtin_divdeu ||
  2989. BuiltinID == PPC::BI__builtin_bpermd;
  2990. bool IsTarget64Bit = Context.getTargetInfo()
  2991. .getTypeWidth(Context
  2992. .getTargetInfo()
  2993. .getIntPtrType()) == 64;
  2994. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2995. BuiltinID == PPC::BI__builtin_divweu ||
  2996. BuiltinID == PPC::BI__builtin_divde ||
  2997. BuiltinID == PPC::BI__builtin_divdeu;
  2998. if (Is64BitBltin && !IsTarget64Bit)
  2999. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  3000. << TheCall->getSourceRange();
  3001. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  3002. (BuiltinID == PPC::BI__builtin_bpermd &&
  3003. !Context.getTargetInfo().hasFeature("bpermd")))
  3004. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3005. << TheCall->getSourceRange();
  3006. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  3007. if (!Context.getTargetInfo().hasFeature("vsx"))
  3008. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  3009. << TheCall->getSourceRange();
  3010. return false;
  3011. };
  3012. switch (BuiltinID) {
  3013. default: return false;
  3014. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  3015. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  3016. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  3017. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3018. case PPC::BI__builtin_tbegin:
  3019. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  3020. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  3021. case PPC::BI__builtin_tabortwc:
  3022. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  3023. case PPC::BI__builtin_tabortwci:
  3024. case PPC::BI__builtin_tabortdci:
  3025. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  3026. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  3027. case PPC::BI__builtin_vsx_xxpermdi:
  3028. case PPC::BI__builtin_vsx_xxsldwi:
  3029. return SemaBuiltinVSX(TheCall);
  3030. case PPC::BI__builtin_unpack_vector_int128:
  3031. return SemaVSXCheck(TheCall) ||
  3032. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  3033. case PPC::BI__builtin_pack_vector_int128:
  3034. return SemaVSXCheck(TheCall);
  3035. }
  3036. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3037. }
  3038. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  3039. CallExpr *TheCall) {
  3040. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  3041. Expr *Arg = TheCall->getArg(0);
  3042. llvm::APSInt AbortCode(32);
  3043. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  3044. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  3045. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  3046. << Arg->getSourceRange();
  3047. }
  3048. // For intrinsics which take an immediate value as part of the instruction,
  3049. // range check them here.
  3050. unsigned i = 0, l = 0, u = 0;
  3051. switch (BuiltinID) {
  3052. default: return false;
  3053. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  3054. case SystemZ::BI__builtin_s390_verimb:
  3055. case SystemZ::BI__builtin_s390_verimh:
  3056. case SystemZ::BI__builtin_s390_verimf:
  3057. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  3058. case SystemZ::BI__builtin_s390_vfaeb:
  3059. case SystemZ::BI__builtin_s390_vfaeh:
  3060. case SystemZ::BI__builtin_s390_vfaef:
  3061. case SystemZ::BI__builtin_s390_vfaebs:
  3062. case SystemZ::BI__builtin_s390_vfaehs:
  3063. case SystemZ::BI__builtin_s390_vfaefs:
  3064. case SystemZ::BI__builtin_s390_vfaezb:
  3065. case SystemZ::BI__builtin_s390_vfaezh:
  3066. case SystemZ::BI__builtin_s390_vfaezf:
  3067. case SystemZ::BI__builtin_s390_vfaezbs:
  3068. case SystemZ::BI__builtin_s390_vfaezhs:
  3069. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  3070. case SystemZ::BI__builtin_s390_vfisb:
  3071. case SystemZ::BI__builtin_s390_vfidb:
  3072. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  3073. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  3074. case SystemZ::BI__builtin_s390_vftcisb:
  3075. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  3076. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  3077. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  3078. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  3079. case SystemZ::BI__builtin_s390_vstrcb:
  3080. case SystemZ::BI__builtin_s390_vstrch:
  3081. case SystemZ::BI__builtin_s390_vstrcf:
  3082. case SystemZ::BI__builtin_s390_vstrczb:
  3083. case SystemZ::BI__builtin_s390_vstrczh:
  3084. case SystemZ::BI__builtin_s390_vstrczf:
  3085. case SystemZ::BI__builtin_s390_vstrcbs:
  3086. case SystemZ::BI__builtin_s390_vstrchs:
  3087. case SystemZ::BI__builtin_s390_vstrcfs:
  3088. case SystemZ::BI__builtin_s390_vstrczbs:
  3089. case SystemZ::BI__builtin_s390_vstrczhs:
  3090. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3091. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3092. case SystemZ::BI__builtin_s390_vfminsb:
  3093. case SystemZ::BI__builtin_s390_vfmaxsb:
  3094. case SystemZ::BI__builtin_s390_vfmindb:
  3095. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3096. case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
  3097. case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
  3098. }
  3099. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3100. }
  3101. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3102. /// This checks that the target supports __builtin_cpu_supports and
  3103. /// that the string argument is constant and valid.
  3104. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3105. Expr *Arg = TheCall->getArg(0);
  3106. // Check if the argument is a string literal.
  3107. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3108. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3109. << Arg->getSourceRange();
  3110. // Check the contents of the string.
  3111. StringRef Feature =
  3112. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3113. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3114. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3115. << Arg->getSourceRange();
  3116. return false;
  3117. }
  3118. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3119. /// This checks that the target supports __builtin_cpu_is and
  3120. /// that the string argument is constant and valid.
  3121. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3122. Expr *Arg = TheCall->getArg(0);
  3123. // Check if the argument is a string literal.
  3124. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3125. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3126. << Arg->getSourceRange();
  3127. // Check the contents of the string.
  3128. StringRef Feature =
  3129. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3130. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3131. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3132. << Arg->getSourceRange();
  3133. return false;
  3134. }
  3135. // Check if the rounding mode is legal.
  3136. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3137. // Indicates if this instruction has rounding control or just SAE.
  3138. bool HasRC = false;
  3139. unsigned ArgNum = 0;
  3140. switch (BuiltinID) {
  3141. default:
  3142. return false;
  3143. case X86::BI__builtin_ia32_vcvttsd2si32:
  3144. case X86::BI__builtin_ia32_vcvttsd2si64:
  3145. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3146. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3147. case X86::BI__builtin_ia32_vcvttss2si32:
  3148. case X86::BI__builtin_ia32_vcvttss2si64:
  3149. case X86::BI__builtin_ia32_vcvttss2usi32:
  3150. case X86::BI__builtin_ia32_vcvttss2usi64:
  3151. ArgNum = 1;
  3152. break;
  3153. case X86::BI__builtin_ia32_maxpd512:
  3154. case X86::BI__builtin_ia32_maxps512:
  3155. case X86::BI__builtin_ia32_minpd512:
  3156. case X86::BI__builtin_ia32_minps512:
  3157. ArgNum = 2;
  3158. break;
  3159. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3160. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3161. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3162. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3163. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3164. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3165. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3166. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3167. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3168. case X86::BI__builtin_ia32_exp2pd_mask:
  3169. case X86::BI__builtin_ia32_exp2ps_mask:
  3170. case X86::BI__builtin_ia32_getexppd512_mask:
  3171. case X86::BI__builtin_ia32_getexpps512_mask:
  3172. case X86::BI__builtin_ia32_rcp28pd_mask:
  3173. case X86::BI__builtin_ia32_rcp28ps_mask:
  3174. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3175. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3176. case X86::BI__builtin_ia32_vcomisd:
  3177. case X86::BI__builtin_ia32_vcomiss:
  3178. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3179. ArgNum = 3;
  3180. break;
  3181. case X86::BI__builtin_ia32_cmppd512_mask:
  3182. case X86::BI__builtin_ia32_cmpps512_mask:
  3183. case X86::BI__builtin_ia32_cmpsd_mask:
  3184. case X86::BI__builtin_ia32_cmpss_mask:
  3185. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3186. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3187. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3188. case X86::BI__builtin_ia32_getmantpd512_mask:
  3189. case X86::BI__builtin_ia32_getmantps512_mask:
  3190. case X86::BI__builtin_ia32_maxsd_round_mask:
  3191. case X86::BI__builtin_ia32_maxss_round_mask:
  3192. case X86::BI__builtin_ia32_minsd_round_mask:
  3193. case X86::BI__builtin_ia32_minss_round_mask:
  3194. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3195. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3196. case X86::BI__builtin_ia32_reducepd512_mask:
  3197. case X86::BI__builtin_ia32_reduceps512_mask:
  3198. case X86::BI__builtin_ia32_rndscalepd_mask:
  3199. case X86::BI__builtin_ia32_rndscaleps_mask:
  3200. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3201. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3202. ArgNum = 4;
  3203. break;
  3204. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3205. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3206. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3207. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3208. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3209. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3210. case X86::BI__builtin_ia32_fixupimmss_mask:
  3211. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3212. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3213. case X86::BI__builtin_ia32_getmantss_round_mask:
  3214. case X86::BI__builtin_ia32_rangepd512_mask:
  3215. case X86::BI__builtin_ia32_rangeps512_mask:
  3216. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3217. case X86::BI__builtin_ia32_rangess128_round_mask:
  3218. case X86::BI__builtin_ia32_reducesd_mask:
  3219. case X86::BI__builtin_ia32_reducess_mask:
  3220. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3221. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3222. ArgNum = 5;
  3223. break;
  3224. case X86::BI__builtin_ia32_vcvtsd2si64:
  3225. case X86::BI__builtin_ia32_vcvtsd2si32:
  3226. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3227. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3228. case X86::BI__builtin_ia32_vcvtss2si32:
  3229. case X86::BI__builtin_ia32_vcvtss2si64:
  3230. case X86::BI__builtin_ia32_vcvtss2usi32:
  3231. case X86::BI__builtin_ia32_vcvtss2usi64:
  3232. case X86::BI__builtin_ia32_sqrtpd512:
  3233. case X86::BI__builtin_ia32_sqrtps512:
  3234. ArgNum = 1;
  3235. HasRC = true;
  3236. break;
  3237. case X86::BI__builtin_ia32_addpd512:
  3238. case X86::BI__builtin_ia32_addps512:
  3239. case X86::BI__builtin_ia32_divpd512:
  3240. case X86::BI__builtin_ia32_divps512:
  3241. case X86::BI__builtin_ia32_mulpd512:
  3242. case X86::BI__builtin_ia32_mulps512:
  3243. case X86::BI__builtin_ia32_subpd512:
  3244. case X86::BI__builtin_ia32_subps512:
  3245. case X86::BI__builtin_ia32_cvtsi2sd64:
  3246. case X86::BI__builtin_ia32_cvtsi2ss32:
  3247. case X86::BI__builtin_ia32_cvtsi2ss64:
  3248. case X86::BI__builtin_ia32_cvtusi2sd64:
  3249. case X86::BI__builtin_ia32_cvtusi2ss32:
  3250. case X86::BI__builtin_ia32_cvtusi2ss64:
  3251. ArgNum = 2;
  3252. HasRC = true;
  3253. break;
  3254. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3255. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3256. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3257. case X86::BI__builtin_ia32_cvtpd2dq512_mask:
  3258. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3259. case X86::BI__builtin_ia32_cvtpd2udq512_mask:
  3260. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3261. case X86::BI__builtin_ia32_cvtps2dq512_mask:
  3262. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3263. case X86::BI__builtin_ia32_cvtps2udq512_mask:
  3264. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3265. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3266. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3267. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3268. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3269. ArgNum = 3;
  3270. HasRC = true;
  3271. break;
  3272. case X86::BI__builtin_ia32_addss_round_mask:
  3273. case X86::BI__builtin_ia32_addsd_round_mask:
  3274. case X86::BI__builtin_ia32_divss_round_mask:
  3275. case X86::BI__builtin_ia32_divsd_round_mask:
  3276. case X86::BI__builtin_ia32_mulss_round_mask:
  3277. case X86::BI__builtin_ia32_mulsd_round_mask:
  3278. case X86::BI__builtin_ia32_subss_round_mask:
  3279. case X86::BI__builtin_ia32_subsd_round_mask:
  3280. case X86::BI__builtin_ia32_scalefpd512_mask:
  3281. case X86::BI__builtin_ia32_scalefps512_mask:
  3282. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3283. case X86::BI__builtin_ia32_scalefss_round_mask:
  3284. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3285. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3286. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3287. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3288. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3289. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3290. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3291. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3292. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3293. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3294. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3295. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3296. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3297. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3298. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3299. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3300. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3301. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3302. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3303. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3304. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3305. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3306. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3307. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3308. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3309. ArgNum = 4;
  3310. HasRC = true;
  3311. break;
  3312. }
  3313. llvm::APSInt Result;
  3314. // We can't check the value of a dependent argument.
  3315. Expr *Arg = TheCall->getArg(ArgNum);
  3316. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3317. return false;
  3318. // Check constant-ness first.
  3319. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3320. return true;
  3321. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3322. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3323. // combined with ROUND_NO_EXC.
  3324. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3325. Result == 8/*ROUND_NO_EXC*/ ||
  3326. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3327. return false;
  3328. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3329. << Arg->getSourceRange();
  3330. }
  3331. // Check if the gather/scatter scale is legal.
  3332. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3333. CallExpr *TheCall) {
  3334. unsigned ArgNum = 0;
  3335. switch (BuiltinID) {
  3336. default:
  3337. return false;
  3338. case X86::BI__builtin_ia32_gatherpfdpd:
  3339. case X86::BI__builtin_ia32_gatherpfdps:
  3340. case X86::BI__builtin_ia32_gatherpfqpd:
  3341. case X86::BI__builtin_ia32_gatherpfqps:
  3342. case X86::BI__builtin_ia32_scatterpfdpd:
  3343. case X86::BI__builtin_ia32_scatterpfdps:
  3344. case X86::BI__builtin_ia32_scatterpfqpd:
  3345. case X86::BI__builtin_ia32_scatterpfqps:
  3346. ArgNum = 3;
  3347. break;
  3348. case X86::BI__builtin_ia32_gatherd_pd:
  3349. case X86::BI__builtin_ia32_gatherd_pd256:
  3350. case X86::BI__builtin_ia32_gatherq_pd:
  3351. case X86::BI__builtin_ia32_gatherq_pd256:
  3352. case X86::BI__builtin_ia32_gatherd_ps:
  3353. case X86::BI__builtin_ia32_gatherd_ps256:
  3354. case X86::BI__builtin_ia32_gatherq_ps:
  3355. case X86::BI__builtin_ia32_gatherq_ps256:
  3356. case X86::BI__builtin_ia32_gatherd_q:
  3357. case X86::BI__builtin_ia32_gatherd_q256:
  3358. case X86::BI__builtin_ia32_gatherq_q:
  3359. case X86::BI__builtin_ia32_gatherq_q256:
  3360. case X86::BI__builtin_ia32_gatherd_d:
  3361. case X86::BI__builtin_ia32_gatherd_d256:
  3362. case X86::BI__builtin_ia32_gatherq_d:
  3363. case X86::BI__builtin_ia32_gatherq_d256:
  3364. case X86::BI__builtin_ia32_gather3div2df:
  3365. case X86::BI__builtin_ia32_gather3div2di:
  3366. case X86::BI__builtin_ia32_gather3div4df:
  3367. case X86::BI__builtin_ia32_gather3div4di:
  3368. case X86::BI__builtin_ia32_gather3div4sf:
  3369. case X86::BI__builtin_ia32_gather3div4si:
  3370. case X86::BI__builtin_ia32_gather3div8sf:
  3371. case X86::BI__builtin_ia32_gather3div8si:
  3372. case X86::BI__builtin_ia32_gather3siv2df:
  3373. case X86::BI__builtin_ia32_gather3siv2di:
  3374. case X86::BI__builtin_ia32_gather3siv4df:
  3375. case X86::BI__builtin_ia32_gather3siv4di:
  3376. case X86::BI__builtin_ia32_gather3siv4sf:
  3377. case X86::BI__builtin_ia32_gather3siv4si:
  3378. case X86::BI__builtin_ia32_gather3siv8sf:
  3379. case X86::BI__builtin_ia32_gather3siv8si:
  3380. case X86::BI__builtin_ia32_gathersiv8df:
  3381. case X86::BI__builtin_ia32_gathersiv16sf:
  3382. case X86::BI__builtin_ia32_gatherdiv8df:
  3383. case X86::BI__builtin_ia32_gatherdiv16sf:
  3384. case X86::BI__builtin_ia32_gathersiv8di:
  3385. case X86::BI__builtin_ia32_gathersiv16si:
  3386. case X86::BI__builtin_ia32_gatherdiv8di:
  3387. case X86::BI__builtin_ia32_gatherdiv16si:
  3388. case X86::BI__builtin_ia32_scatterdiv2df:
  3389. case X86::BI__builtin_ia32_scatterdiv2di:
  3390. case X86::BI__builtin_ia32_scatterdiv4df:
  3391. case X86::BI__builtin_ia32_scatterdiv4di:
  3392. case X86::BI__builtin_ia32_scatterdiv4sf:
  3393. case X86::BI__builtin_ia32_scatterdiv4si:
  3394. case X86::BI__builtin_ia32_scatterdiv8sf:
  3395. case X86::BI__builtin_ia32_scatterdiv8si:
  3396. case X86::BI__builtin_ia32_scattersiv2df:
  3397. case X86::BI__builtin_ia32_scattersiv2di:
  3398. case X86::BI__builtin_ia32_scattersiv4df:
  3399. case X86::BI__builtin_ia32_scattersiv4di:
  3400. case X86::BI__builtin_ia32_scattersiv4sf:
  3401. case X86::BI__builtin_ia32_scattersiv4si:
  3402. case X86::BI__builtin_ia32_scattersiv8sf:
  3403. case X86::BI__builtin_ia32_scattersiv8si:
  3404. case X86::BI__builtin_ia32_scattersiv8df:
  3405. case X86::BI__builtin_ia32_scattersiv16sf:
  3406. case X86::BI__builtin_ia32_scatterdiv8df:
  3407. case X86::BI__builtin_ia32_scatterdiv16sf:
  3408. case X86::BI__builtin_ia32_scattersiv8di:
  3409. case X86::BI__builtin_ia32_scattersiv16si:
  3410. case X86::BI__builtin_ia32_scatterdiv8di:
  3411. case X86::BI__builtin_ia32_scatterdiv16si:
  3412. ArgNum = 4;
  3413. break;
  3414. }
  3415. llvm::APSInt Result;
  3416. // We can't check the value of a dependent argument.
  3417. Expr *Arg = TheCall->getArg(ArgNum);
  3418. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3419. return false;
  3420. // Check constant-ness first.
  3421. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3422. return true;
  3423. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3424. return false;
  3425. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3426. << Arg->getSourceRange();
  3427. }
  3428. static bool isX86_32Builtin(unsigned BuiltinID) {
  3429. // These builtins only work on x86-32 targets.
  3430. switch (BuiltinID) {
  3431. case X86::BI__builtin_ia32_readeflags_u32:
  3432. case X86::BI__builtin_ia32_writeeflags_u32:
  3433. return true;
  3434. }
  3435. return false;
  3436. }
  3437. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3438. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3439. return SemaBuiltinCpuSupports(*this, TheCall);
  3440. if (BuiltinID == X86::BI__builtin_cpu_is)
  3441. return SemaBuiltinCpuIs(*this, TheCall);
  3442. // Check for 32-bit only builtins on a 64-bit target.
  3443. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3444. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3445. return Diag(TheCall->getCallee()->getBeginLoc(),
  3446. diag::err_32_bit_builtin_64_bit_tgt);
  3447. // If the intrinsic has rounding or SAE make sure its valid.
  3448. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3449. return true;
  3450. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3451. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3452. return true;
  3453. // For intrinsics which take an immediate value as part of the instruction,
  3454. // range check them here.
  3455. int i = 0, l = 0, u = 0;
  3456. switch (BuiltinID) {
  3457. default:
  3458. return false;
  3459. case X86::BI__builtin_ia32_vec_ext_v2si:
  3460. case X86::BI__builtin_ia32_vec_ext_v2di:
  3461. case X86::BI__builtin_ia32_vextractf128_pd256:
  3462. case X86::BI__builtin_ia32_vextractf128_ps256:
  3463. case X86::BI__builtin_ia32_vextractf128_si256:
  3464. case X86::BI__builtin_ia32_extract128i256:
  3465. case X86::BI__builtin_ia32_extractf64x4_mask:
  3466. case X86::BI__builtin_ia32_extracti64x4_mask:
  3467. case X86::BI__builtin_ia32_extractf32x8_mask:
  3468. case X86::BI__builtin_ia32_extracti32x8_mask:
  3469. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3470. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3471. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3472. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3473. i = 1; l = 0; u = 1;
  3474. break;
  3475. case X86::BI__builtin_ia32_vec_set_v2di:
  3476. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3477. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3478. case X86::BI__builtin_ia32_vinsertf128_si256:
  3479. case X86::BI__builtin_ia32_insert128i256:
  3480. case X86::BI__builtin_ia32_insertf32x8:
  3481. case X86::BI__builtin_ia32_inserti32x8:
  3482. case X86::BI__builtin_ia32_insertf64x4:
  3483. case X86::BI__builtin_ia32_inserti64x4:
  3484. case X86::BI__builtin_ia32_insertf64x2_256:
  3485. case X86::BI__builtin_ia32_inserti64x2_256:
  3486. case X86::BI__builtin_ia32_insertf32x4_256:
  3487. case X86::BI__builtin_ia32_inserti32x4_256:
  3488. i = 2; l = 0; u = 1;
  3489. break;
  3490. case X86::BI__builtin_ia32_vpermilpd:
  3491. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3492. case X86::BI__builtin_ia32_vec_ext_v4si:
  3493. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3494. case X86::BI__builtin_ia32_vec_ext_v4di:
  3495. case X86::BI__builtin_ia32_extractf32x4_mask:
  3496. case X86::BI__builtin_ia32_extracti32x4_mask:
  3497. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3498. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3499. i = 1; l = 0; u = 3;
  3500. break;
  3501. case X86::BI_mm_prefetch:
  3502. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3503. case X86::BI__builtin_ia32_vec_ext_v8si:
  3504. i = 1; l = 0; u = 7;
  3505. break;
  3506. case X86::BI__builtin_ia32_sha1rnds4:
  3507. case X86::BI__builtin_ia32_blendpd:
  3508. case X86::BI__builtin_ia32_shufpd:
  3509. case X86::BI__builtin_ia32_vec_set_v4hi:
  3510. case X86::BI__builtin_ia32_vec_set_v4si:
  3511. case X86::BI__builtin_ia32_vec_set_v4di:
  3512. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3513. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3514. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3515. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3516. case X86::BI__builtin_ia32_insertf64x2_512:
  3517. case X86::BI__builtin_ia32_inserti64x2_512:
  3518. case X86::BI__builtin_ia32_insertf32x4:
  3519. case X86::BI__builtin_ia32_inserti32x4:
  3520. i = 2; l = 0; u = 3;
  3521. break;
  3522. case X86::BI__builtin_ia32_vpermil2pd:
  3523. case X86::BI__builtin_ia32_vpermil2pd256:
  3524. case X86::BI__builtin_ia32_vpermil2ps:
  3525. case X86::BI__builtin_ia32_vpermil2ps256:
  3526. i = 3; l = 0; u = 3;
  3527. break;
  3528. case X86::BI__builtin_ia32_cmpb128_mask:
  3529. case X86::BI__builtin_ia32_cmpw128_mask:
  3530. case X86::BI__builtin_ia32_cmpd128_mask:
  3531. case X86::BI__builtin_ia32_cmpq128_mask:
  3532. case X86::BI__builtin_ia32_cmpb256_mask:
  3533. case X86::BI__builtin_ia32_cmpw256_mask:
  3534. case X86::BI__builtin_ia32_cmpd256_mask:
  3535. case X86::BI__builtin_ia32_cmpq256_mask:
  3536. case X86::BI__builtin_ia32_cmpb512_mask:
  3537. case X86::BI__builtin_ia32_cmpw512_mask:
  3538. case X86::BI__builtin_ia32_cmpd512_mask:
  3539. case X86::BI__builtin_ia32_cmpq512_mask:
  3540. case X86::BI__builtin_ia32_ucmpb128_mask:
  3541. case X86::BI__builtin_ia32_ucmpw128_mask:
  3542. case X86::BI__builtin_ia32_ucmpd128_mask:
  3543. case X86::BI__builtin_ia32_ucmpq128_mask:
  3544. case X86::BI__builtin_ia32_ucmpb256_mask:
  3545. case X86::BI__builtin_ia32_ucmpw256_mask:
  3546. case X86::BI__builtin_ia32_ucmpd256_mask:
  3547. case X86::BI__builtin_ia32_ucmpq256_mask:
  3548. case X86::BI__builtin_ia32_ucmpb512_mask:
  3549. case X86::BI__builtin_ia32_ucmpw512_mask:
  3550. case X86::BI__builtin_ia32_ucmpd512_mask:
  3551. case X86::BI__builtin_ia32_ucmpq512_mask:
  3552. case X86::BI__builtin_ia32_vpcomub:
  3553. case X86::BI__builtin_ia32_vpcomuw:
  3554. case X86::BI__builtin_ia32_vpcomud:
  3555. case X86::BI__builtin_ia32_vpcomuq:
  3556. case X86::BI__builtin_ia32_vpcomb:
  3557. case X86::BI__builtin_ia32_vpcomw:
  3558. case X86::BI__builtin_ia32_vpcomd:
  3559. case X86::BI__builtin_ia32_vpcomq:
  3560. case X86::BI__builtin_ia32_vec_set_v8hi:
  3561. case X86::BI__builtin_ia32_vec_set_v8si:
  3562. i = 2; l = 0; u = 7;
  3563. break;
  3564. case X86::BI__builtin_ia32_vpermilpd256:
  3565. case X86::BI__builtin_ia32_roundps:
  3566. case X86::BI__builtin_ia32_roundpd:
  3567. case X86::BI__builtin_ia32_roundps256:
  3568. case X86::BI__builtin_ia32_roundpd256:
  3569. case X86::BI__builtin_ia32_getmantpd128_mask:
  3570. case X86::BI__builtin_ia32_getmantpd256_mask:
  3571. case X86::BI__builtin_ia32_getmantps128_mask:
  3572. case X86::BI__builtin_ia32_getmantps256_mask:
  3573. case X86::BI__builtin_ia32_getmantpd512_mask:
  3574. case X86::BI__builtin_ia32_getmantps512_mask:
  3575. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3576. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3577. i = 1; l = 0; u = 15;
  3578. break;
  3579. case X86::BI__builtin_ia32_pblendd128:
  3580. case X86::BI__builtin_ia32_blendps:
  3581. case X86::BI__builtin_ia32_blendpd256:
  3582. case X86::BI__builtin_ia32_shufpd256:
  3583. case X86::BI__builtin_ia32_roundss:
  3584. case X86::BI__builtin_ia32_roundsd:
  3585. case X86::BI__builtin_ia32_rangepd128_mask:
  3586. case X86::BI__builtin_ia32_rangepd256_mask:
  3587. case X86::BI__builtin_ia32_rangepd512_mask:
  3588. case X86::BI__builtin_ia32_rangeps128_mask:
  3589. case X86::BI__builtin_ia32_rangeps256_mask:
  3590. case X86::BI__builtin_ia32_rangeps512_mask:
  3591. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3592. case X86::BI__builtin_ia32_getmantss_round_mask:
  3593. case X86::BI__builtin_ia32_vec_set_v16qi:
  3594. case X86::BI__builtin_ia32_vec_set_v16hi:
  3595. i = 2; l = 0; u = 15;
  3596. break;
  3597. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3598. i = 1; l = 0; u = 31;
  3599. break;
  3600. case X86::BI__builtin_ia32_cmpps:
  3601. case X86::BI__builtin_ia32_cmpss:
  3602. case X86::BI__builtin_ia32_cmppd:
  3603. case X86::BI__builtin_ia32_cmpsd:
  3604. case X86::BI__builtin_ia32_cmpps256:
  3605. case X86::BI__builtin_ia32_cmppd256:
  3606. case X86::BI__builtin_ia32_cmpps128_mask:
  3607. case X86::BI__builtin_ia32_cmppd128_mask:
  3608. case X86::BI__builtin_ia32_cmpps256_mask:
  3609. case X86::BI__builtin_ia32_cmppd256_mask:
  3610. case X86::BI__builtin_ia32_cmpps512_mask:
  3611. case X86::BI__builtin_ia32_cmppd512_mask:
  3612. case X86::BI__builtin_ia32_cmpsd_mask:
  3613. case X86::BI__builtin_ia32_cmpss_mask:
  3614. case X86::BI__builtin_ia32_vec_set_v32qi:
  3615. i = 2; l = 0; u = 31;
  3616. break;
  3617. case X86::BI__builtin_ia32_permdf256:
  3618. case X86::BI__builtin_ia32_permdi256:
  3619. case X86::BI__builtin_ia32_permdf512:
  3620. case X86::BI__builtin_ia32_permdi512:
  3621. case X86::BI__builtin_ia32_vpermilps:
  3622. case X86::BI__builtin_ia32_vpermilps256:
  3623. case X86::BI__builtin_ia32_vpermilpd512:
  3624. case X86::BI__builtin_ia32_vpermilps512:
  3625. case X86::BI__builtin_ia32_pshufd:
  3626. case X86::BI__builtin_ia32_pshufd256:
  3627. case X86::BI__builtin_ia32_pshufd512:
  3628. case X86::BI__builtin_ia32_pshufhw:
  3629. case X86::BI__builtin_ia32_pshufhw256:
  3630. case X86::BI__builtin_ia32_pshufhw512:
  3631. case X86::BI__builtin_ia32_pshuflw:
  3632. case X86::BI__builtin_ia32_pshuflw256:
  3633. case X86::BI__builtin_ia32_pshuflw512:
  3634. case X86::BI__builtin_ia32_vcvtps2ph:
  3635. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3636. case X86::BI__builtin_ia32_vcvtps2ph256:
  3637. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3638. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3639. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3640. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3641. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3642. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3643. case X86::BI__builtin_ia32_rndscaleps_mask:
  3644. case X86::BI__builtin_ia32_rndscalepd_mask:
  3645. case X86::BI__builtin_ia32_reducepd128_mask:
  3646. case X86::BI__builtin_ia32_reducepd256_mask:
  3647. case X86::BI__builtin_ia32_reducepd512_mask:
  3648. case X86::BI__builtin_ia32_reduceps128_mask:
  3649. case X86::BI__builtin_ia32_reduceps256_mask:
  3650. case X86::BI__builtin_ia32_reduceps512_mask:
  3651. case X86::BI__builtin_ia32_prold512:
  3652. case X86::BI__builtin_ia32_prolq512:
  3653. case X86::BI__builtin_ia32_prold128:
  3654. case X86::BI__builtin_ia32_prold256:
  3655. case X86::BI__builtin_ia32_prolq128:
  3656. case X86::BI__builtin_ia32_prolq256:
  3657. case X86::BI__builtin_ia32_prord512:
  3658. case X86::BI__builtin_ia32_prorq512:
  3659. case X86::BI__builtin_ia32_prord128:
  3660. case X86::BI__builtin_ia32_prord256:
  3661. case X86::BI__builtin_ia32_prorq128:
  3662. case X86::BI__builtin_ia32_prorq256:
  3663. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3664. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3665. case X86::BI__builtin_ia32_fpclassps128_mask:
  3666. case X86::BI__builtin_ia32_fpclassps256_mask:
  3667. case X86::BI__builtin_ia32_fpclassps512_mask:
  3668. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3669. case X86::BI__builtin_ia32_fpclasssd_mask:
  3670. case X86::BI__builtin_ia32_fpclassss_mask:
  3671. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3672. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3673. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3674. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3675. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3676. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3677. case X86::BI__builtin_ia32_kshiftliqi:
  3678. case X86::BI__builtin_ia32_kshiftlihi:
  3679. case X86::BI__builtin_ia32_kshiftlisi:
  3680. case X86::BI__builtin_ia32_kshiftlidi:
  3681. case X86::BI__builtin_ia32_kshiftriqi:
  3682. case X86::BI__builtin_ia32_kshiftrihi:
  3683. case X86::BI__builtin_ia32_kshiftrisi:
  3684. case X86::BI__builtin_ia32_kshiftridi:
  3685. i = 1; l = 0; u = 255;
  3686. break;
  3687. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3688. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3689. case X86::BI__builtin_ia32_vperm2f128_si256:
  3690. case X86::BI__builtin_ia32_permti256:
  3691. case X86::BI__builtin_ia32_pblendw128:
  3692. case X86::BI__builtin_ia32_pblendw256:
  3693. case X86::BI__builtin_ia32_blendps256:
  3694. case X86::BI__builtin_ia32_pblendd256:
  3695. case X86::BI__builtin_ia32_palignr128:
  3696. case X86::BI__builtin_ia32_palignr256:
  3697. case X86::BI__builtin_ia32_palignr512:
  3698. case X86::BI__builtin_ia32_alignq512:
  3699. case X86::BI__builtin_ia32_alignd512:
  3700. case X86::BI__builtin_ia32_alignd128:
  3701. case X86::BI__builtin_ia32_alignd256:
  3702. case X86::BI__builtin_ia32_alignq128:
  3703. case X86::BI__builtin_ia32_alignq256:
  3704. case X86::BI__builtin_ia32_vcomisd:
  3705. case X86::BI__builtin_ia32_vcomiss:
  3706. case X86::BI__builtin_ia32_shuf_f32x4:
  3707. case X86::BI__builtin_ia32_shuf_f64x2:
  3708. case X86::BI__builtin_ia32_shuf_i32x4:
  3709. case X86::BI__builtin_ia32_shuf_i64x2:
  3710. case X86::BI__builtin_ia32_shufpd512:
  3711. case X86::BI__builtin_ia32_shufps:
  3712. case X86::BI__builtin_ia32_shufps256:
  3713. case X86::BI__builtin_ia32_shufps512:
  3714. case X86::BI__builtin_ia32_dbpsadbw128:
  3715. case X86::BI__builtin_ia32_dbpsadbw256:
  3716. case X86::BI__builtin_ia32_dbpsadbw512:
  3717. case X86::BI__builtin_ia32_vpshldd128:
  3718. case X86::BI__builtin_ia32_vpshldd256:
  3719. case X86::BI__builtin_ia32_vpshldd512:
  3720. case X86::BI__builtin_ia32_vpshldq128:
  3721. case X86::BI__builtin_ia32_vpshldq256:
  3722. case X86::BI__builtin_ia32_vpshldq512:
  3723. case X86::BI__builtin_ia32_vpshldw128:
  3724. case X86::BI__builtin_ia32_vpshldw256:
  3725. case X86::BI__builtin_ia32_vpshldw512:
  3726. case X86::BI__builtin_ia32_vpshrdd128:
  3727. case X86::BI__builtin_ia32_vpshrdd256:
  3728. case X86::BI__builtin_ia32_vpshrdd512:
  3729. case X86::BI__builtin_ia32_vpshrdq128:
  3730. case X86::BI__builtin_ia32_vpshrdq256:
  3731. case X86::BI__builtin_ia32_vpshrdq512:
  3732. case X86::BI__builtin_ia32_vpshrdw128:
  3733. case X86::BI__builtin_ia32_vpshrdw256:
  3734. case X86::BI__builtin_ia32_vpshrdw512:
  3735. i = 2; l = 0; u = 255;
  3736. break;
  3737. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3738. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3739. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3740. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3741. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3742. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3743. case X86::BI__builtin_ia32_fixupimmss_mask:
  3744. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3745. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3746. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3747. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3748. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3749. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3750. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3751. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3752. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3753. case X86::BI__builtin_ia32_pternlogd512_mask:
  3754. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3755. case X86::BI__builtin_ia32_pternlogq512_mask:
  3756. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3757. case X86::BI__builtin_ia32_pternlogd128_mask:
  3758. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3759. case X86::BI__builtin_ia32_pternlogd256_mask:
  3760. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3761. case X86::BI__builtin_ia32_pternlogq128_mask:
  3762. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3763. case X86::BI__builtin_ia32_pternlogq256_mask:
  3764. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3765. i = 3; l = 0; u = 255;
  3766. break;
  3767. case X86::BI__builtin_ia32_gatherpfdpd:
  3768. case X86::BI__builtin_ia32_gatherpfdps:
  3769. case X86::BI__builtin_ia32_gatherpfqpd:
  3770. case X86::BI__builtin_ia32_gatherpfqps:
  3771. case X86::BI__builtin_ia32_scatterpfdpd:
  3772. case X86::BI__builtin_ia32_scatterpfdps:
  3773. case X86::BI__builtin_ia32_scatterpfqpd:
  3774. case X86::BI__builtin_ia32_scatterpfqps:
  3775. i = 4; l = 2; u = 3;
  3776. break;
  3777. case X86::BI__builtin_ia32_reducesd_mask:
  3778. case X86::BI__builtin_ia32_reducess_mask:
  3779. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3780. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3781. i = 4; l = 0; u = 255;
  3782. break;
  3783. }
  3784. // Note that we don't force a hard error on the range check here, allowing
  3785. // template-generated or macro-generated dead code to potentially have out-of-
  3786. // range values. These need to code generate, but don't need to necessarily
  3787. // make any sense. We use a warning that defaults to an error.
  3788. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3789. }
  3790. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3791. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3792. /// Returns true when the format fits the function and the FormatStringInfo has
  3793. /// been populated.
  3794. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3795. FormatStringInfo *FSI) {
  3796. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3797. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3798. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3799. // The way the format attribute works in GCC, the implicit this argument
  3800. // of member functions is counted. However, it doesn't appear in our own
  3801. // lists, so decrement format_idx in that case.
  3802. if (IsCXXMember) {
  3803. if(FSI->FormatIdx == 0)
  3804. return false;
  3805. --FSI->FormatIdx;
  3806. if (FSI->FirstDataArg != 0)
  3807. --FSI->FirstDataArg;
  3808. }
  3809. return true;
  3810. }
  3811. /// Checks if a the given expression evaluates to null.
  3812. ///
  3813. /// Returns true if the value evaluates to null.
  3814. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3815. // If the expression has non-null type, it doesn't evaluate to null.
  3816. if (auto nullability
  3817. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3818. if (*nullability == NullabilityKind::NonNull)
  3819. return false;
  3820. }
  3821. // As a special case, transparent unions initialized with zero are
  3822. // considered null for the purposes of the nonnull attribute.
  3823. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3824. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3825. if (const CompoundLiteralExpr *CLE =
  3826. dyn_cast<CompoundLiteralExpr>(Expr))
  3827. if (const InitListExpr *ILE =
  3828. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3829. Expr = ILE->getInit(0);
  3830. }
  3831. bool Result;
  3832. return (!Expr->isValueDependent() &&
  3833. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3834. !Result);
  3835. }
  3836. static void CheckNonNullArgument(Sema &S,
  3837. const Expr *ArgExpr,
  3838. SourceLocation CallSiteLoc) {
  3839. if (CheckNonNullExpr(S, ArgExpr))
  3840. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3841. S.PDiag(diag::warn_null_arg)
  3842. << ArgExpr->getSourceRange());
  3843. }
  3844. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3845. FormatStringInfo FSI;
  3846. if ((GetFormatStringType(Format) == FST_NSString) &&
  3847. getFormatStringInfo(Format, false, &FSI)) {
  3848. Idx = FSI.FormatIdx;
  3849. return true;
  3850. }
  3851. return false;
  3852. }
  3853. /// Diagnose use of %s directive in an NSString which is being passed
  3854. /// as formatting string to formatting method.
  3855. static void
  3856. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3857. const NamedDecl *FDecl,
  3858. Expr **Args,
  3859. unsigned NumArgs) {
  3860. unsigned Idx = 0;
  3861. bool Format = false;
  3862. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3863. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3864. Idx = 2;
  3865. Format = true;
  3866. }
  3867. else
  3868. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3869. if (S.GetFormatNSStringIdx(I, Idx)) {
  3870. Format = true;
  3871. break;
  3872. }
  3873. }
  3874. if (!Format || NumArgs <= Idx)
  3875. return;
  3876. const Expr *FormatExpr = Args[Idx];
  3877. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3878. FormatExpr = CSCE->getSubExpr();
  3879. const StringLiteral *FormatString;
  3880. if (const ObjCStringLiteral *OSL =
  3881. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3882. FormatString = OSL->getString();
  3883. else
  3884. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3885. if (!FormatString)
  3886. return;
  3887. if (S.FormatStringHasSArg(FormatString)) {
  3888. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3889. << "%s" << 1 << 1;
  3890. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3891. << FDecl->getDeclName();
  3892. }
  3893. }
  3894. /// Determine whether the given type has a non-null nullability annotation.
  3895. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3896. if (auto nullability = type->getNullability(ctx))
  3897. return *nullability == NullabilityKind::NonNull;
  3898. return false;
  3899. }
  3900. static void CheckNonNullArguments(Sema &S,
  3901. const NamedDecl *FDecl,
  3902. const FunctionProtoType *Proto,
  3903. ArrayRef<const Expr *> Args,
  3904. SourceLocation CallSiteLoc) {
  3905. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3906. // Already checked by by constant evaluator.
  3907. if (S.isConstantEvaluated())
  3908. return;
  3909. // Check the attributes attached to the method/function itself.
  3910. llvm::SmallBitVector NonNullArgs;
  3911. if (FDecl) {
  3912. // Handle the nonnull attribute on the function/method declaration itself.
  3913. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3914. if (!NonNull->args_size()) {
  3915. // Easy case: all pointer arguments are nonnull.
  3916. for (const auto *Arg : Args)
  3917. if (S.isValidPointerAttrType(Arg->getType()))
  3918. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3919. return;
  3920. }
  3921. for (const ParamIdx &Idx : NonNull->args()) {
  3922. unsigned IdxAST = Idx.getASTIndex();
  3923. if (IdxAST >= Args.size())
  3924. continue;
  3925. if (NonNullArgs.empty())
  3926. NonNullArgs.resize(Args.size());
  3927. NonNullArgs.set(IdxAST);
  3928. }
  3929. }
  3930. }
  3931. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3932. // Handle the nonnull attribute on the parameters of the
  3933. // function/method.
  3934. ArrayRef<ParmVarDecl*> parms;
  3935. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3936. parms = FD->parameters();
  3937. else
  3938. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3939. unsigned ParamIndex = 0;
  3940. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3941. I != E; ++I, ++ParamIndex) {
  3942. const ParmVarDecl *PVD = *I;
  3943. if (PVD->hasAttr<NonNullAttr>() ||
  3944. isNonNullType(S.Context, PVD->getType())) {
  3945. if (NonNullArgs.empty())
  3946. NonNullArgs.resize(Args.size());
  3947. NonNullArgs.set(ParamIndex);
  3948. }
  3949. }
  3950. } else {
  3951. // If we have a non-function, non-method declaration but no
  3952. // function prototype, try to dig out the function prototype.
  3953. if (!Proto) {
  3954. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3955. QualType type = VD->getType().getNonReferenceType();
  3956. if (auto pointerType = type->getAs<PointerType>())
  3957. type = pointerType->getPointeeType();
  3958. else if (auto blockType = type->getAs<BlockPointerType>())
  3959. type = blockType->getPointeeType();
  3960. // FIXME: data member pointers?
  3961. // Dig out the function prototype, if there is one.
  3962. Proto = type->getAs<FunctionProtoType>();
  3963. }
  3964. }
  3965. // Fill in non-null argument information from the nullability
  3966. // information on the parameter types (if we have them).
  3967. if (Proto) {
  3968. unsigned Index = 0;
  3969. for (auto paramType : Proto->getParamTypes()) {
  3970. if (isNonNullType(S.Context, paramType)) {
  3971. if (NonNullArgs.empty())
  3972. NonNullArgs.resize(Args.size());
  3973. NonNullArgs.set(Index);
  3974. }
  3975. ++Index;
  3976. }
  3977. }
  3978. }
  3979. // Check for non-null arguments.
  3980. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3981. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3982. if (NonNullArgs[ArgIndex])
  3983. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3984. }
  3985. }
  3986. /// Handles the checks for format strings, non-POD arguments to vararg
  3987. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3988. /// attributes.
  3989. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3990. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3991. bool IsMemberFunction, SourceLocation Loc,
  3992. SourceRange Range, VariadicCallType CallType) {
  3993. // FIXME: We should check as much as we can in the template definition.
  3994. if (CurContext->isDependentContext())
  3995. return;
  3996. // Printf and scanf checking.
  3997. llvm::SmallBitVector CheckedVarArgs;
  3998. if (FDecl) {
  3999. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  4000. // Only create vector if there are format attributes.
  4001. CheckedVarArgs.resize(Args.size());
  4002. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  4003. CheckedVarArgs);
  4004. }
  4005. }
  4006. // Refuse POD arguments that weren't caught by the format string
  4007. // checks above.
  4008. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  4009. if (CallType != VariadicDoesNotApply &&
  4010. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  4011. unsigned NumParams = Proto ? Proto->getNumParams()
  4012. : FDecl && isa<FunctionDecl>(FDecl)
  4013. ? cast<FunctionDecl>(FDecl)->getNumParams()
  4014. : FDecl && isa<ObjCMethodDecl>(FDecl)
  4015. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  4016. : 0;
  4017. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  4018. // Args[ArgIdx] can be null in malformed code.
  4019. if (const Expr *Arg = Args[ArgIdx]) {
  4020. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  4021. checkVariadicArgument(Arg, CallType);
  4022. }
  4023. }
  4024. }
  4025. if (FDecl || Proto) {
  4026. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  4027. // Type safety checking.
  4028. if (FDecl) {
  4029. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  4030. CheckArgumentWithTypeTag(I, Args, Loc);
  4031. }
  4032. }
  4033. if (FD)
  4034. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  4035. }
  4036. /// CheckConstructorCall - Check a constructor call for correctness and safety
  4037. /// properties not enforced by the C type system.
  4038. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  4039. ArrayRef<const Expr *> Args,
  4040. const FunctionProtoType *Proto,
  4041. SourceLocation Loc) {
  4042. VariadicCallType CallType =
  4043. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  4044. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  4045. Loc, SourceRange(), CallType);
  4046. }
  4047. /// CheckFunctionCall - Check a direct function call for various correctness
  4048. /// and safety properties not strictly enforced by the C type system.
  4049. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  4050. const FunctionProtoType *Proto) {
  4051. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  4052. isa<CXXMethodDecl>(FDecl);
  4053. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  4054. IsMemberOperatorCall;
  4055. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  4056. TheCall->getCallee());
  4057. Expr** Args = TheCall->getArgs();
  4058. unsigned NumArgs = TheCall->getNumArgs();
  4059. Expr *ImplicitThis = nullptr;
  4060. if (IsMemberOperatorCall) {
  4061. // If this is a call to a member operator, hide the first argument
  4062. // from checkCall.
  4063. // FIXME: Our choice of AST representation here is less than ideal.
  4064. ImplicitThis = Args[0];
  4065. ++Args;
  4066. --NumArgs;
  4067. } else if (IsMemberFunction)
  4068. ImplicitThis =
  4069. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  4070. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  4071. IsMemberFunction, TheCall->getRParenLoc(),
  4072. TheCall->getCallee()->getSourceRange(), CallType);
  4073. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4074. // None of the checks below are needed for functions that don't have
  4075. // simple names (e.g., C++ conversion functions).
  4076. if (!FnInfo)
  4077. return false;
  4078. CheckAbsoluteValueFunction(TheCall, FDecl);
  4079. CheckMaxUnsignedZero(TheCall, FDecl);
  4080. if (getLangOpts().ObjC)
  4081. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  4082. unsigned CMId = FDecl->getMemoryFunctionKind();
  4083. if (CMId == 0)
  4084. return false;
  4085. // Handle memory setting and copying functions.
  4086. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  4087. CheckStrlcpycatArguments(TheCall, FnInfo);
  4088. else if (CMId == Builtin::BIstrncat)
  4089. CheckStrncatArguments(TheCall, FnInfo);
  4090. else
  4091. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  4092. return false;
  4093. }
  4094. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4095. ArrayRef<const Expr *> Args) {
  4096. VariadicCallType CallType =
  4097. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4098. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4099. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4100. CallType);
  4101. return false;
  4102. }
  4103. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4104. const FunctionProtoType *Proto) {
  4105. QualType Ty;
  4106. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4107. Ty = V->getType().getNonReferenceType();
  4108. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4109. Ty = F->getType().getNonReferenceType();
  4110. else
  4111. return false;
  4112. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4113. !Ty->isFunctionProtoType())
  4114. return false;
  4115. VariadicCallType CallType;
  4116. if (!Proto || !Proto->isVariadic()) {
  4117. CallType = VariadicDoesNotApply;
  4118. } else if (Ty->isBlockPointerType()) {
  4119. CallType = VariadicBlock;
  4120. } else { // Ty->isFunctionPointerType()
  4121. CallType = VariadicFunction;
  4122. }
  4123. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4124. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4125. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4126. TheCall->getCallee()->getSourceRange(), CallType);
  4127. return false;
  4128. }
  4129. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4130. /// such as function pointers returned from functions.
  4131. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4132. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4133. TheCall->getCallee());
  4134. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4135. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4136. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4137. TheCall->getCallee()->getSourceRange(), CallType);
  4138. return false;
  4139. }
  4140. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4141. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4142. return false;
  4143. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4144. switch (Op) {
  4145. case AtomicExpr::AO__c11_atomic_init:
  4146. case AtomicExpr::AO__opencl_atomic_init:
  4147. llvm_unreachable("There is no ordering argument for an init");
  4148. case AtomicExpr::AO__c11_atomic_load:
  4149. case AtomicExpr::AO__opencl_atomic_load:
  4150. case AtomicExpr::AO__atomic_load_n:
  4151. case AtomicExpr::AO__atomic_load:
  4152. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4153. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4154. case AtomicExpr::AO__c11_atomic_store:
  4155. case AtomicExpr::AO__opencl_atomic_store:
  4156. case AtomicExpr::AO__atomic_store:
  4157. case AtomicExpr::AO__atomic_store_n:
  4158. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4159. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4160. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4161. default:
  4162. return true;
  4163. }
  4164. }
  4165. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4166. AtomicExpr::AtomicOp Op) {
  4167. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4168. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4169. // All the non-OpenCL operations take one of the following forms.
  4170. // The OpenCL operations take the __c11 forms with one extra argument for
  4171. // synchronization scope.
  4172. enum {
  4173. // C __c11_atomic_init(A *, C)
  4174. Init,
  4175. // C __c11_atomic_load(A *, int)
  4176. Load,
  4177. // void __atomic_load(A *, CP, int)
  4178. LoadCopy,
  4179. // void __atomic_store(A *, CP, int)
  4180. Copy,
  4181. // C __c11_atomic_add(A *, M, int)
  4182. Arithmetic,
  4183. // C __atomic_exchange_n(A *, CP, int)
  4184. Xchg,
  4185. // void __atomic_exchange(A *, C *, CP, int)
  4186. GNUXchg,
  4187. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4188. C11CmpXchg,
  4189. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4190. GNUCmpXchg
  4191. } Form = Init;
  4192. const unsigned NumForm = GNUCmpXchg + 1;
  4193. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4194. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4195. // where:
  4196. // C is an appropriate type,
  4197. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4198. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4199. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4200. // the int parameters are for orderings.
  4201. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4202. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4203. "need to update code for modified forms");
  4204. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4205. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4206. AtomicExpr::AO__atomic_load,
  4207. "need to update code for modified C11 atomics");
  4208. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4209. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4210. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4211. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4212. IsOpenCL;
  4213. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4214. Op == AtomicExpr::AO__atomic_store_n ||
  4215. Op == AtomicExpr::AO__atomic_exchange_n ||
  4216. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4217. bool IsAddSub = false;
  4218. bool IsMinMax = false;
  4219. switch (Op) {
  4220. case AtomicExpr::AO__c11_atomic_init:
  4221. case AtomicExpr::AO__opencl_atomic_init:
  4222. Form = Init;
  4223. break;
  4224. case AtomicExpr::AO__c11_atomic_load:
  4225. case AtomicExpr::AO__opencl_atomic_load:
  4226. case AtomicExpr::AO__atomic_load_n:
  4227. Form = Load;
  4228. break;
  4229. case AtomicExpr::AO__atomic_load:
  4230. Form = LoadCopy;
  4231. break;
  4232. case AtomicExpr::AO__c11_atomic_store:
  4233. case AtomicExpr::AO__opencl_atomic_store:
  4234. case AtomicExpr::AO__atomic_store:
  4235. case AtomicExpr::AO__atomic_store_n:
  4236. Form = Copy;
  4237. break;
  4238. case AtomicExpr::AO__c11_atomic_fetch_add:
  4239. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4240. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4241. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4242. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4243. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4244. case AtomicExpr::AO__atomic_fetch_add:
  4245. case AtomicExpr::AO__atomic_fetch_sub:
  4246. case AtomicExpr::AO__atomic_add_fetch:
  4247. case AtomicExpr::AO__atomic_sub_fetch:
  4248. IsAddSub = true;
  4249. LLVM_FALLTHROUGH;
  4250. case AtomicExpr::AO__c11_atomic_fetch_and:
  4251. case AtomicExpr::AO__c11_atomic_fetch_or:
  4252. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4253. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4254. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4255. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4256. case AtomicExpr::AO__atomic_fetch_and:
  4257. case AtomicExpr::AO__atomic_fetch_or:
  4258. case AtomicExpr::AO__atomic_fetch_xor:
  4259. case AtomicExpr::AO__atomic_fetch_nand:
  4260. case AtomicExpr::AO__atomic_and_fetch:
  4261. case AtomicExpr::AO__atomic_or_fetch:
  4262. case AtomicExpr::AO__atomic_xor_fetch:
  4263. case AtomicExpr::AO__atomic_nand_fetch:
  4264. Form = Arithmetic;
  4265. break;
  4266. case AtomicExpr::AO__atomic_fetch_min:
  4267. case AtomicExpr::AO__atomic_fetch_max:
  4268. IsMinMax = true;
  4269. Form = Arithmetic;
  4270. break;
  4271. case AtomicExpr::AO__c11_atomic_exchange:
  4272. case AtomicExpr::AO__opencl_atomic_exchange:
  4273. case AtomicExpr::AO__atomic_exchange_n:
  4274. Form = Xchg;
  4275. break;
  4276. case AtomicExpr::AO__atomic_exchange:
  4277. Form = GNUXchg;
  4278. break;
  4279. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4280. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4281. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4282. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4283. Form = C11CmpXchg;
  4284. break;
  4285. case AtomicExpr::AO__atomic_compare_exchange:
  4286. case AtomicExpr::AO__atomic_compare_exchange_n:
  4287. Form = GNUCmpXchg;
  4288. break;
  4289. }
  4290. unsigned AdjustedNumArgs = NumArgs[Form];
  4291. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4292. ++AdjustedNumArgs;
  4293. // Check we have the right number of arguments.
  4294. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4295. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4296. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4297. << TheCall->getCallee()->getSourceRange();
  4298. return ExprError();
  4299. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4300. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4301. diag::err_typecheck_call_too_many_args)
  4302. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4303. << TheCall->getCallee()->getSourceRange();
  4304. return ExprError();
  4305. }
  4306. // Inspect the first argument of the atomic operation.
  4307. Expr *Ptr = TheCall->getArg(0);
  4308. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4309. if (ConvertedPtr.isInvalid())
  4310. return ExprError();
  4311. Ptr = ConvertedPtr.get();
  4312. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4313. if (!pointerType) {
  4314. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4315. << Ptr->getType() << Ptr->getSourceRange();
  4316. return ExprError();
  4317. }
  4318. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4319. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4320. QualType ValType = AtomTy; // 'C'
  4321. if (IsC11) {
  4322. if (!AtomTy->isAtomicType()) {
  4323. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4324. << Ptr->getType() << Ptr->getSourceRange();
  4325. return ExprError();
  4326. }
  4327. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4328. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4329. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4330. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4331. << Ptr->getSourceRange();
  4332. return ExprError();
  4333. }
  4334. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4335. } else if (Form != Load && Form != LoadCopy) {
  4336. if (ValType.isConstQualified()) {
  4337. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4338. << Ptr->getType() << Ptr->getSourceRange();
  4339. return ExprError();
  4340. }
  4341. }
  4342. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4343. if (Form == Arithmetic) {
  4344. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4345. if (IsAddSub && !ValType->isIntegerType()
  4346. && !ValType->isPointerType()) {
  4347. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4348. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4349. return ExprError();
  4350. }
  4351. if (IsMinMax) {
  4352. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4353. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4354. BT->getKind() != BuiltinType::UInt)) {
  4355. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4356. return ExprError();
  4357. }
  4358. }
  4359. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4360. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4361. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4362. return ExprError();
  4363. }
  4364. if (IsC11 && ValType->isPointerType() &&
  4365. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4366. diag::err_incomplete_type)) {
  4367. return ExprError();
  4368. }
  4369. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4370. // For __atomic_*_n operations, the value type must be a scalar integral or
  4371. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4372. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4373. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4374. return ExprError();
  4375. }
  4376. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4377. !AtomTy->isScalarType()) {
  4378. // For GNU atomics, require a trivially-copyable type. This is not part of
  4379. // the GNU atomics specification, but we enforce it for sanity.
  4380. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4381. << Ptr->getType() << Ptr->getSourceRange();
  4382. return ExprError();
  4383. }
  4384. switch (ValType.getObjCLifetime()) {
  4385. case Qualifiers::OCL_None:
  4386. case Qualifiers::OCL_ExplicitNone:
  4387. // okay
  4388. break;
  4389. case Qualifiers::OCL_Weak:
  4390. case Qualifiers::OCL_Strong:
  4391. case Qualifiers::OCL_Autoreleasing:
  4392. // FIXME: Can this happen? By this point, ValType should be known
  4393. // to be trivially copyable.
  4394. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4395. << ValType << Ptr->getSourceRange();
  4396. return ExprError();
  4397. }
  4398. // All atomic operations have an overload which takes a pointer to a volatile
  4399. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4400. // into the result or the other operands. Similarly atomic_load takes a
  4401. // pointer to a const 'A'.
  4402. ValType.removeLocalVolatile();
  4403. ValType.removeLocalConst();
  4404. QualType ResultType = ValType;
  4405. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4406. Form == Init)
  4407. ResultType = Context.VoidTy;
  4408. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4409. ResultType = Context.BoolTy;
  4410. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4411. // arguments are actually passed as pointers.
  4412. QualType ByValType = ValType; // 'CP'
  4413. bool IsPassedByAddress = false;
  4414. if (!IsC11 && !IsN) {
  4415. ByValType = Ptr->getType();
  4416. IsPassedByAddress = true;
  4417. }
  4418. // The first argument's non-CV pointer type is used to deduce the type of
  4419. // subsequent arguments, except for:
  4420. // - weak flag (always converted to bool)
  4421. // - memory order (always converted to int)
  4422. // - scope (always converted to int)
  4423. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4424. QualType Ty;
  4425. if (i < NumVals[Form] + 1) {
  4426. switch (i) {
  4427. case 0:
  4428. // The first argument is always a pointer. It has a fixed type.
  4429. // It is always dereferenced, a nullptr is undefined.
  4430. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4431. // Nothing else to do: we already know all we want about this pointer.
  4432. continue;
  4433. case 1:
  4434. // The second argument is the non-atomic operand. For arithmetic, this
  4435. // is always passed by value, and for a compare_exchange it is always
  4436. // passed by address. For the rest, GNU uses by-address and C11 uses
  4437. // by-value.
  4438. assert(Form != Load);
  4439. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4440. Ty = ValType;
  4441. else if (Form == Copy || Form == Xchg) {
  4442. if (IsPassedByAddress)
  4443. // The value pointer is always dereferenced, a nullptr is undefined.
  4444. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4445. Ty = ByValType;
  4446. } else if (Form == Arithmetic)
  4447. Ty = Context.getPointerDiffType();
  4448. else {
  4449. Expr *ValArg = TheCall->getArg(i);
  4450. // The value pointer is always dereferenced, a nullptr is undefined.
  4451. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4452. LangAS AS = LangAS::Default;
  4453. // Keep address space of non-atomic pointer type.
  4454. if (const PointerType *PtrTy =
  4455. ValArg->getType()->getAs<PointerType>()) {
  4456. AS = PtrTy->getPointeeType().getAddressSpace();
  4457. }
  4458. Ty = Context.getPointerType(
  4459. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4460. }
  4461. break;
  4462. case 2:
  4463. // The third argument to compare_exchange / GNU exchange is the desired
  4464. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4465. if (IsPassedByAddress)
  4466. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4467. Ty = ByValType;
  4468. break;
  4469. case 3:
  4470. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4471. Ty = Context.BoolTy;
  4472. break;
  4473. }
  4474. } else {
  4475. // The order(s) and scope are always converted to int.
  4476. Ty = Context.IntTy;
  4477. }
  4478. InitializedEntity Entity =
  4479. InitializedEntity::InitializeParameter(Context, Ty, false);
  4480. ExprResult Arg = TheCall->getArg(i);
  4481. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4482. if (Arg.isInvalid())
  4483. return true;
  4484. TheCall->setArg(i, Arg.get());
  4485. }
  4486. // Permute the arguments into a 'consistent' order.
  4487. SmallVector<Expr*, 5> SubExprs;
  4488. SubExprs.push_back(Ptr);
  4489. switch (Form) {
  4490. case Init:
  4491. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4492. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4493. break;
  4494. case Load:
  4495. SubExprs.push_back(TheCall->getArg(1)); // Order
  4496. break;
  4497. case LoadCopy:
  4498. case Copy:
  4499. case Arithmetic:
  4500. case Xchg:
  4501. SubExprs.push_back(TheCall->getArg(2)); // Order
  4502. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4503. break;
  4504. case GNUXchg:
  4505. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4506. SubExprs.push_back(TheCall->getArg(3)); // Order
  4507. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4508. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4509. break;
  4510. case C11CmpXchg:
  4511. SubExprs.push_back(TheCall->getArg(3)); // Order
  4512. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4513. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4514. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4515. break;
  4516. case GNUCmpXchg:
  4517. SubExprs.push_back(TheCall->getArg(4)); // Order
  4518. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4519. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4520. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4521. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4522. break;
  4523. }
  4524. if (SubExprs.size() >= 2 && Form != Init) {
  4525. llvm::APSInt Result(32);
  4526. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4527. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4528. Diag(SubExprs[1]->getBeginLoc(),
  4529. diag::warn_atomic_op_has_invalid_memory_order)
  4530. << SubExprs[1]->getSourceRange();
  4531. }
  4532. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4533. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4534. llvm::APSInt Result(32);
  4535. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4536. !ScopeModel->isValid(Result.getZExtValue())) {
  4537. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4538. << Scope->getSourceRange();
  4539. }
  4540. SubExprs.push_back(Scope);
  4541. }
  4542. AtomicExpr *AE =
  4543. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4544. ResultType, Op, TheCall->getRParenLoc());
  4545. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4546. Op == AtomicExpr::AO__c11_atomic_store ||
  4547. Op == AtomicExpr::AO__opencl_atomic_load ||
  4548. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4549. Context.AtomicUsesUnsupportedLibcall(AE))
  4550. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4551. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4552. Op == AtomicExpr::AO__opencl_atomic_load)
  4553. ? 0
  4554. : 1);
  4555. return AE;
  4556. }
  4557. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4558. /// normal type-checking on the given argument, updating the call in
  4559. /// place. This is useful when a builtin function requires custom
  4560. /// type-checking for some of its arguments but not necessarily all of
  4561. /// them.
  4562. ///
  4563. /// Returns true on error.
  4564. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4565. FunctionDecl *Fn = E->getDirectCallee();
  4566. assert(Fn && "builtin call without direct callee!");
  4567. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4568. InitializedEntity Entity =
  4569. InitializedEntity::InitializeParameter(S.Context, Param);
  4570. ExprResult Arg = E->getArg(0);
  4571. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4572. if (Arg.isInvalid())
  4573. return true;
  4574. E->setArg(ArgIndex, Arg.get());
  4575. return false;
  4576. }
  4577. /// We have a call to a function like __sync_fetch_and_add, which is an
  4578. /// overloaded function based on the pointer type of its first argument.
  4579. /// The main BuildCallExpr routines have already promoted the types of
  4580. /// arguments because all of these calls are prototyped as void(...).
  4581. ///
  4582. /// This function goes through and does final semantic checking for these
  4583. /// builtins, as well as generating any warnings.
  4584. ExprResult
  4585. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4586. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4587. Expr *Callee = TheCall->getCallee();
  4588. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4589. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4590. // Ensure that we have at least one argument to do type inference from.
  4591. if (TheCall->getNumArgs() < 1) {
  4592. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4593. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4594. return ExprError();
  4595. }
  4596. // Inspect the first argument of the atomic builtin. This should always be
  4597. // a pointer type, whose element is an integral scalar or pointer type.
  4598. // Because it is a pointer type, we don't have to worry about any implicit
  4599. // casts here.
  4600. // FIXME: We don't allow floating point scalars as input.
  4601. Expr *FirstArg = TheCall->getArg(0);
  4602. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4603. if (FirstArgResult.isInvalid())
  4604. return ExprError();
  4605. FirstArg = FirstArgResult.get();
  4606. TheCall->setArg(0, FirstArg);
  4607. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4608. if (!pointerType) {
  4609. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4610. << FirstArg->getType() << FirstArg->getSourceRange();
  4611. return ExprError();
  4612. }
  4613. QualType ValType = pointerType->getPointeeType();
  4614. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4615. !ValType->isBlockPointerType()) {
  4616. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4617. << FirstArg->getType() << FirstArg->getSourceRange();
  4618. return ExprError();
  4619. }
  4620. if (ValType.isConstQualified()) {
  4621. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4622. << FirstArg->getType() << FirstArg->getSourceRange();
  4623. return ExprError();
  4624. }
  4625. switch (ValType.getObjCLifetime()) {
  4626. case Qualifiers::OCL_None:
  4627. case Qualifiers::OCL_ExplicitNone:
  4628. // okay
  4629. break;
  4630. case Qualifiers::OCL_Weak:
  4631. case Qualifiers::OCL_Strong:
  4632. case Qualifiers::OCL_Autoreleasing:
  4633. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4634. << ValType << FirstArg->getSourceRange();
  4635. return ExprError();
  4636. }
  4637. // Strip any qualifiers off ValType.
  4638. ValType = ValType.getUnqualifiedType();
  4639. // The majority of builtins return a value, but a few have special return
  4640. // types, so allow them to override appropriately below.
  4641. QualType ResultType = ValType;
  4642. // We need to figure out which concrete builtin this maps onto. For example,
  4643. // __sync_fetch_and_add with a 2 byte object turns into
  4644. // __sync_fetch_and_add_2.
  4645. #define BUILTIN_ROW(x) \
  4646. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4647. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4648. static const unsigned BuiltinIndices[][5] = {
  4649. BUILTIN_ROW(__sync_fetch_and_add),
  4650. BUILTIN_ROW(__sync_fetch_and_sub),
  4651. BUILTIN_ROW(__sync_fetch_and_or),
  4652. BUILTIN_ROW(__sync_fetch_and_and),
  4653. BUILTIN_ROW(__sync_fetch_and_xor),
  4654. BUILTIN_ROW(__sync_fetch_and_nand),
  4655. BUILTIN_ROW(__sync_add_and_fetch),
  4656. BUILTIN_ROW(__sync_sub_and_fetch),
  4657. BUILTIN_ROW(__sync_and_and_fetch),
  4658. BUILTIN_ROW(__sync_or_and_fetch),
  4659. BUILTIN_ROW(__sync_xor_and_fetch),
  4660. BUILTIN_ROW(__sync_nand_and_fetch),
  4661. BUILTIN_ROW(__sync_val_compare_and_swap),
  4662. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4663. BUILTIN_ROW(__sync_lock_test_and_set),
  4664. BUILTIN_ROW(__sync_lock_release),
  4665. BUILTIN_ROW(__sync_swap)
  4666. };
  4667. #undef BUILTIN_ROW
  4668. // Determine the index of the size.
  4669. unsigned SizeIndex;
  4670. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4671. case 1: SizeIndex = 0; break;
  4672. case 2: SizeIndex = 1; break;
  4673. case 4: SizeIndex = 2; break;
  4674. case 8: SizeIndex = 3; break;
  4675. case 16: SizeIndex = 4; break;
  4676. default:
  4677. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4678. << FirstArg->getType() << FirstArg->getSourceRange();
  4679. return ExprError();
  4680. }
  4681. // Each of these builtins has one pointer argument, followed by some number of
  4682. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4683. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4684. // as the number of fixed args.
  4685. unsigned BuiltinID = FDecl->getBuiltinID();
  4686. unsigned BuiltinIndex, NumFixed = 1;
  4687. bool WarnAboutSemanticsChange = false;
  4688. switch (BuiltinID) {
  4689. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4690. case Builtin::BI__sync_fetch_and_add:
  4691. case Builtin::BI__sync_fetch_and_add_1:
  4692. case Builtin::BI__sync_fetch_and_add_2:
  4693. case Builtin::BI__sync_fetch_and_add_4:
  4694. case Builtin::BI__sync_fetch_and_add_8:
  4695. case Builtin::BI__sync_fetch_and_add_16:
  4696. BuiltinIndex = 0;
  4697. break;
  4698. case Builtin::BI__sync_fetch_and_sub:
  4699. case Builtin::BI__sync_fetch_and_sub_1:
  4700. case Builtin::BI__sync_fetch_and_sub_2:
  4701. case Builtin::BI__sync_fetch_and_sub_4:
  4702. case Builtin::BI__sync_fetch_and_sub_8:
  4703. case Builtin::BI__sync_fetch_and_sub_16:
  4704. BuiltinIndex = 1;
  4705. break;
  4706. case Builtin::BI__sync_fetch_and_or:
  4707. case Builtin::BI__sync_fetch_and_or_1:
  4708. case Builtin::BI__sync_fetch_and_or_2:
  4709. case Builtin::BI__sync_fetch_and_or_4:
  4710. case Builtin::BI__sync_fetch_and_or_8:
  4711. case Builtin::BI__sync_fetch_and_or_16:
  4712. BuiltinIndex = 2;
  4713. break;
  4714. case Builtin::BI__sync_fetch_and_and:
  4715. case Builtin::BI__sync_fetch_and_and_1:
  4716. case Builtin::BI__sync_fetch_and_and_2:
  4717. case Builtin::BI__sync_fetch_and_and_4:
  4718. case Builtin::BI__sync_fetch_and_and_8:
  4719. case Builtin::BI__sync_fetch_and_and_16:
  4720. BuiltinIndex = 3;
  4721. break;
  4722. case Builtin::BI__sync_fetch_and_xor:
  4723. case Builtin::BI__sync_fetch_and_xor_1:
  4724. case Builtin::BI__sync_fetch_and_xor_2:
  4725. case Builtin::BI__sync_fetch_and_xor_4:
  4726. case Builtin::BI__sync_fetch_and_xor_8:
  4727. case Builtin::BI__sync_fetch_and_xor_16:
  4728. BuiltinIndex = 4;
  4729. break;
  4730. case Builtin::BI__sync_fetch_and_nand:
  4731. case Builtin::BI__sync_fetch_and_nand_1:
  4732. case Builtin::BI__sync_fetch_and_nand_2:
  4733. case Builtin::BI__sync_fetch_and_nand_4:
  4734. case Builtin::BI__sync_fetch_and_nand_8:
  4735. case Builtin::BI__sync_fetch_and_nand_16:
  4736. BuiltinIndex = 5;
  4737. WarnAboutSemanticsChange = true;
  4738. break;
  4739. case Builtin::BI__sync_add_and_fetch:
  4740. case Builtin::BI__sync_add_and_fetch_1:
  4741. case Builtin::BI__sync_add_and_fetch_2:
  4742. case Builtin::BI__sync_add_and_fetch_4:
  4743. case Builtin::BI__sync_add_and_fetch_8:
  4744. case Builtin::BI__sync_add_and_fetch_16:
  4745. BuiltinIndex = 6;
  4746. break;
  4747. case Builtin::BI__sync_sub_and_fetch:
  4748. case Builtin::BI__sync_sub_and_fetch_1:
  4749. case Builtin::BI__sync_sub_and_fetch_2:
  4750. case Builtin::BI__sync_sub_and_fetch_4:
  4751. case Builtin::BI__sync_sub_and_fetch_8:
  4752. case Builtin::BI__sync_sub_and_fetch_16:
  4753. BuiltinIndex = 7;
  4754. break;
  4755. case Builtin::BI__sync_and_and_fetch:
  4756. case Builtin::BI__sync_and_and_fetch_1:
  4757. case Builtin::BI__sync_and_and_fetch_2:
  4758. case Builtin::BI__sync_and_and_fetch_4:
  4759. case Builtin::BI__sync_and_and_fetch_8:
  4760. case Builtin::BI__sync_and_and_fetch_16:
  4761. BuiltinIndex = 8;
  4762. break;
  4763. case Builtin::BI__sync_or_and_fetch:
  4764. case Builtin::BI__sync_or_and_fetch_1:
  4765. case Builtin::BI__sync_or_and_fetch_2:
  4766. case Builtin::BI__sync_or_and_fetch_4:
  4767. case Builtin::BI__sync_or_and_fetch_8:
  4768. case Builtin::BI__sync_or_and_fetch_16:
  4769. BuiltinIndex = 9;
  4770. break;
  4771. case Builtin::BI__sync_xor_and_fetch:
  4772. case Builtin::BI__sync_xor_and_fetch_1:
  4773. case Builtin::BI__sync_xor_and_fetch_2:
  4774. case Builtin::BI__sync_xor_and_fetch_4:
  4775. case Builtin::BI__sync_xor_and_fetch_8:
  4776. case Builtin::BI__sync_xor_and_fetch_16:
  4777. BuiltinIndex = 10;
  4778. break;
  4779. case Builtin::BI__sync_nand_and_fetch:
  4780. case Builtin::BI__sync_nand_and_fetch_1:
  4781. case Builtin::BI__sync_nand_and_fetch_2:
  4782. case Builtin::BI__sync_nand_and_fetch_4:
  4783. case Builtin::BI__sync_nand_and_fetch_8:
  4784. case Builtin::BI__sync_nand_and_fetch_16:
  4785. BuiltinIndex = 11;
  4786. WarnAboutSemanticsChange = true;
  4787. break;
  4788. case Builtin::BI__sync_val_compare_and_swap:
  4789. case Builtin::BI__sync_val_compare_and_swap_1:
  4790. case Builtin::BI__sync_val_compare_and_swap_2:
  4791. case Builtin::BI__sync_val_compare_and_swap_4:
  4792. case Builtin::BI__sync_val_compare_and_swap_8:
  4793. case Builtin::BI__sync_val_compare_and_swap_16:
  4794. BuiltinIndex = 12;
  4795. NumFixed = 2;
  4796. break;
  4797. case Builtin::BI__sync_bool_compare_and_swap:
  4798. case Builtin::BI__sync_bool_compare_and_swap_1:
  4799. case Builtin::BI__sync_bool_compare_and_swap_2:
  4800. case Builtin::BI__sync_bool_compare_and_swap_4:
  4801. case Builtin::BI__sync_bool_compare_and_swap_8:
  4802. case Builtin::BI__sync_bool_compare_and_swap_16:
  4803. BuiltinIndex = 13;
  4804. NumFixed = 2;
  4805. ResultType = Context.BoolTy;
  4806. break;
  4807. case Builtin::BI__sync_lock_test_and_set:
  4808. case Builtin::BI__sync_lock_test_and_set_1:
  4809. case Builtin::BI__sync_lock_test_and_set_2:
  4810. case Builtin::BI__sync_lock_test_and_set_4:
  4811. case Builtin::BI__sync_lock_test_and_set_8:
  4812. case Builtin::BI__sync_lock_test_and_set_16:
  4813. BuiltinIndex = 14;
  4814. break;
  4815. case Builtin::BI__sync_lock_release:
  4816. case Builtin::BI__sync_lock_release_1:
  4817. case Builtin::BI__sync_lock_release_2:
  4818. case Builtin::BI__sync_lock_release_4:
  4819. case Builtin::BI__sync_lock_release_8:
  4820. case Builtin::BI__sync_lock_release_16:
  4821. BuiltinIndex = 15;
  4822. NumFixed = 0;
  4823. ResultType = Context.VoidTy;
  4824. break;
  4825. case Builtin::BI__sync_swap:
  4826. case Builtin::BI__sync_swap_1:
  4827. case Builtin::BI__sync_swap_2:
  4828. case Builtin::BI__sync_swap_4:
  4829. case Builtin::BI__sync_swap_8:
  4830. case Builtin::BI__sync_swap_16:
  4831. BuiltinIndex = 16;
  4832. break;
  4833. }
  4834. // Now that we know how many fixed arguments we expect, first check that we
  4835. // have at least that many.
  4836. if (TheCall->getNumArgs() < 1+NumFixed) {
  4837. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4838. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4839. << Callee->getSourceRange();
  4840. return ExprError();
  4841. }
  4842. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4843. << Callee->getSourceRange();
  4844. if (WarnAboutSemanticsChange) {
  4845. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4846. << Callee->getSourceRange();
  4847. }
  4848. // Get the decl for the concrete builtin from this, we can tell what the
  4849. // concrete integer type we should convert to is.
  4850. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4851. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4852. FunctionDecl *NewBuiltinDecl;
  4853. if (NewBuiltinID == BuiltinID)
  4854. NewBuiltinDecl = FDecl;
  4855. else {
  4856. // Perform builtin lookup to avoid redeclaring it.
  4857. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4858. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4859. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4860. assert(Res.getFoundDecl());
  4861. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4862. if (!NewBuiltinDecl)
  4863. return ExprError();
  4864. }
  4865. // The first argument --- the pointer --- has a fixed type; we
  4866. // deduce the types of the rest of the arguments accordingly. Walk
  4867. // the remaining arguments, converting them to the deduced value type.
  4868. for (unsigned i = 0; i != NumFixed; ++i) {
  4869. ExprResult Arg = TheCall->getArg(i+1);
  4870. // GCC does an implicit conversion to the pointer or integer ValType. This
  4871. // can fail in some cases (1i -> int**), check for this error case now.
  4872. // Initialize the argument.
  4873. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4874. ValType, /*consume*/ false);
  4875. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4876. if (Arg.isInvalid())
  4877. return ExprError();
  4878. // Okay, we have something that *can* be converted to the right type. Check
  4879. // to see if there is a potentially weird extension going on here. This can
  4880. // happen when you do an atomic operation on something like an char* and
  4881. // pass in 42. The 42 gets converted to char. This is even more strange
  4882. // for things like 45.123 -> char, etc.
  4883. // FIXME: Do this check.
  4884. TheCall->setArg(i+1, Arg.get());
  4885. }
  4886. // Create a new DeclRefExpr to refer to the new decl.
  4887. DeclRefExpr *NewDRE = DeclRefExpr::Create(
  4888. Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
  4889. /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
  4890. DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
  4891. // Set the callee in the CallExpr.
  4892. // FIXME: This loses syntactic information.
  4893. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4894. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4895. CK_BuiltinFnToFnPtr);
  4896. TheCall->setCallee(PromotedCall.get());
  4897. // Change the result type of the call to match the original value type. This
  4898. // is arbitrary, but the codegen for these builtins ins design to handle it
  4899. // gracefully.
  4900. TheCall->setType(ResultType);
  4901. return TheCallResult;
  4902. }
  4903. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4904. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4905. /// overloaded function based on the pointer type of its last argument.
  4906. ///
  4907. /// This function goes through and does final semantic checking for these
  4908. /// builtins.
  4909. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4910. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4911. DeclRefExpr *DRE =
  4912. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4913. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4914. unsigned BuiltinID = FDecl->getBuiltinID();
  4915. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4916. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4917. "Unexpected nontemporal load/store builtin!");
  4918. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4919. unsigned numArgs = isStore ? 2 : 1;
  4920. // Ensure that we have the proper number of arguments.
  4921. if (checkArgCount(*this, TheCall, numArgs))
  4922. return ExprError();
  4923. // Inspect the last argument of the nontemporal builtin. This should always
  4924. // be a pointer type, from which we imply the type of the memory access.
  4925. // Because it is a pointer type, we don't have to worry about any implicit
  4926. // casts here.
  4927. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4928. ExprResult PointerArgResult =
  4929. DefaultFunctionArrayLvalueConversion(PointerArg);
  4930. if (PointerArgResult.isInvalid())
  4931. return ExprError();
  4932. PointerArg = PointerArgResult.get();
  4933. TheCall->setArg(numArgs - 1, PointerArg);
  4934. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4935. if (!pointerType) {
  4936. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4937. << PointerArg->getType() << PointerArg->getSourceRange();
  4938. return ExprError();
  4939. }
  4940. QualType ValType = pointerType->getPointeeType();
  4941. // Strip any qualifiers off ValType.
  4942. ValType = ValType.getUnqualifiedType();
  4943. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4944. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4945. !ValType->isVectorType()) {
  4946. Diag(DRE->getBeginLoc(),
  4947. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4948. << PointerArg->getType() << PointerArg->getSourceRange();
  4949. return ExprError();
  4950. }
  4951. if (!isStore) {
  4952. TheCall->setType(ValType);
  4953. return TheCallResult;
  4954. }
  4955. ExprResult ValArg = TheCall->getArg(0);
  4956. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4957. Context, ValType, /*consume*/ false);
  4958. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4959. if (ValArg.isInvalid())
  4960. return ExprError();
  4961. TheCall->setArg(0, ValArg.get());
  4962. TheCall->setType(Context.VoidTy);
  4963. return TheCallResult;
  4964. }
  4965. /// CheckObjCString - Checks that the argument to the builtin
  4966. /// CFString constructor is correct
  4967. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4968. /// simplify the backend).
  4969. bool Sema::CheckObjCString(Expr *Arg) {
  4970. Arg = Arg->IgnoreParenCasts();
  4971. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4972. if (!Literal || !Literal->isAscii()) {
  4973. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4974. << Arg->getSourceRange();
  4975. return true;
  4976. }
  4977. if (Literal->containsNonAsciiOrNull()) {
  4978. StringRef String = Literal->getString();
  4979. unsigned NumBytes = String.size();
  4980. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4981. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4982. llvm::UTF16 *ToPtr = &ToBuf[0];
  4983. llvm::ConversionResult Result =
  4984. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4985. ToPtr + NumBytes, llvm::strictConversion);
  4986. // Check for conversion failure.
  4987. if (Result != llvm::conversionOK)
  4988. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4989. << Arg->getSourceRange();
  4990. }
  4991. return false;
  4992. }
  4993. /// CheckObjCString - Checks that the format string argument to the os_log()
  4994. /// and os_trace() functions is correct, and converts it to const char *.
  4995. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4996. Arg = Arg->IgnoreParenCasts();
  4997. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4998. if (!Literal) {
  4999. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  5000. Literal = ObjcLiteral->getString();
  5001. }
  5002. }
  5003. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  5004. return ExprError(
  5005. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  5006. << Arg->getSourceRange());
  5007. }
  5008. ExprResult Result(Literal);
  5009. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  5010. InitializedEntity Entity =
  5011. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  5012. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  5013. return Result;
  5014. }
  5015. /// Check that the user is calling the appropriate va_start builtin for the
  5016. /// target and calling convention.
  5017. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  5018. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  5019. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  5020. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  5021. bool IsWindows = TT.isOSWindows();
  5022. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  5023. if (IsX64 || IsAArch64) {
  5024. CallingConv CC = CC_C;
  5025. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  5026. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  5027. if (IsMSVAStart) {
  5028. // Don't allow this in System V ABI functions.
  5029. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  5030. return S.Diag(Fn->getBeginLoc(),
  5031. diag::err_ms_va_start_used_in_sysv_function);
  5032. } else {
  5033. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  5034. // On x64 Windows, don't allow this in System V ABI functions.
  5035. // (Yes, that means there's no corresponding way to support variadic
  5036. // System V ABI functions on Windows.)
  5037. if ((IsWindows && CC == CC_X86_64SysV) ||
  5038. (!IsWindows && CC == CC_Win64))
  5039. return S.Diag(Fn->getBeginLoc(),
  5040. diag::err_va_start_used_in_wrong_abi_function)
  5041. << !IsWindows;
  5042. }
  5043. return false;
  5044. }
  5045. if (IsMSVAStart)
  5046. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  5047. return false;
  5048. }
  5049. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  5050. ParmVarDecl **LastParam = nullptr) {
  5051. // Determine whether the current function, block, or obj-c method is variadic
  5052. // and get its parameter list.
  5053. bool IsVariadic = false;
  5054. ArrayRef<ParmVarDecl *> Params;
  5055. DeclContext *Caller = S.CurContext;
  5056. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  5057. IsVariadic = Block->isVariadic();
  5058. Params = Block->parameters();
  5059. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  5060. IsVariadic = FD->isVariadic();
  5061. Params = FD->parameters();
  5062. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  5063. IsVariadic = MD->isVariadic();
  5064. // FIXME: This isn't correct for methods (results in bogus warning).
  5065. Params = MD->parameters();
  5066. } else if (isa<CapturedDecl>(Caller)) {
  5067. // We don't support va_start in a CapturedDecl.
  5068. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  5069. return true;
  5070. } else {
  5071. // This must be some other declcontext that parses exprs.
  5072. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  5073. return true;
  5074. }
  5075. if (!IsVariadic) {
  5076. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  5077. return true;
  5078. }
  5079. if (LastParam)
  5080. *LastParam = Params.empty() ? nullptr : Params.back();
  5081. return false;
  5082. }
  5083. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  5084. /// for validity. Emit an error and return true on failure; return false
  5085. /// on success.
  5086. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  5087. Expr *Fn = TheCall->getCallee();
  5088. if (checkVAStartABI(*this, BuiltinID, Fn))
  5089. return true;
  5090. if (TheCall->getNumArgs() > 2) {
  5091. Diag(TheCall->getArg(2)->getBeginLoc(),
  5092. diag::err_typecheck_call_too_many_args)
  5093. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5094. << Fn->getSourceRange()
  5095. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5096. (*(TheCall->arg_end() - 1))->getEndLoc());
  5097. return true;
  5098. }
  5099. if (TheCall->getNumArgs() < 2) {
  5100. return Diag(TheCall->getEndLoc(),
  5101. diag::err_typecheck_call_too_few_args_at_least)
  5102. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5103. }
  5104. // Type-check the first argument normally.
  5105. if (checkBuiltinArgument(*this, TheCall, 0))
  5106. return true;
  5107. // Check that the current function is variadic, and get its last parameter.
  5108. ParmVarDecl *LastParam;
  5109. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5110. return true;
  5111. // Verify that the second argument to the builtin is the last argument of the
  5112. // current function or method.
  5113. bool SecondArgIsLastNamedArgument = false;
  5114. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5115. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5116. // block.
  5117. QualType Type;
  5118. SourceLocation ParamLoc;
  5119. bool IsCRegister = false;
  5120. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5121. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5122. SecondArgIsLastNamedArgument = PV == LastParam;
  5123. Type = PV->getType();
  5124. ParamLoc = PV->getLocation();
  5125. IsCRegister =
  5126. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5127. }
  5128. }
  5129. if (!SecondArgIsLastNamedArgument)
  5130. Diag(TheCall->getArg(1)->getBeginLoc(),
  5131. diag::warn_second_arg_of_va_start_not_last_named_param);
  5132. else if (IsCRegister || Type->isReferenceType() ||
  5133. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5134. // Promotable integers are UB, but enumerations need a bit of
  5135. // extra checking to see what their promotable type actually is.
  5136. if (!Type->isPromotableIntegerType())
  5137. return false;
  5138. if (!Type->isEnumeralType())
  5139. return true;
  5140. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5141. return !(ED &&
  5142. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5143. }()) {
  5144. unsigned Reason = 0;
  5145. if (Type->isReferenceType()) Reason = 1;
  5146. else if (IsCRegister) Reason = 2;
  5147. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5148. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5149. }
  5150. TheCall->setType(Context.VoidTy);
  5151. return false;
  5152. }
  5153. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5154. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5155. // const char *named_addr);
  5156. Expr *Func = Call->getCallee();
  5157. if (Call->getNumArgs() < 3)
  5158. return Diag(Call->getEndLoc(),
  5159. diag::err_typecheck_call_too_few_args_at_least)
  5160. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5161. // Type-check the first argument normally.
  5162. if (checkBuiltinArgument(*this, Call, 0))
  5163. return true;
  5164. // Check that the current function is variadic.
  5165. if (checkVAStartIsInVariadicFunction(*this, Func))
  5166. return true;
  5167. // __va_start on Windows does not validate the parameter qualifiers
  5168. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5169. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5170. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5171. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5172. const QualType &ConstCharPtrTy =
  5173. Context.getPointerType(Context.CharTy.withConst());
  5174. if (!Arg1Ty->isPointerType() ||
  5175. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5176. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5177. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5178. << 0 /* qualifier difference */
  5179. << 3 /* parameter mismatch */
  5180. << 2 << Arg1->getType() << ConstCharPtrTy;
  5181. const QualType SizeTy = Context.getSizeType();
  5182. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5183. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5184. << Arg2->getType() << SizeTy << 1 /* different class */
  5185. << 0 /* qualifier difference */
  5186. << 3 /* parameter mismatch */
  5187. << 3 << Arg2->getType() << SizeTy;
  5188. return false;
  5189. }
  5190. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5191. /// friends. This is declared to take (...), so we have to check everything.
  5192. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5193. if (TheCall->getNumArgs() < 2)
  5194. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5195. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5196. if (TheCall->getNumArgs() > 2)
  5197. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5198. diag::err_typecheck_call_too_many_args)
  5199. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5200. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5201. (*(TheCall->arg_end() - 1))->getEndLoc());
  5202. ExprResult OrigArg0 = TheCall->getArg(0);
  5203. ExprResult OrigArg1 = TheCall->getArg(1);
  5204. // Do standard promotions between the two arguments, returning their common
  5205. // type.
  5206. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5207. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5208. return true;
  5209. // Make sure any conversions are pushed back into the call; this is
  5210. // type safe since unordered compare builtins are declared as "_Bool
  5211. // foo(...)".
  5212. TheCall->setArg(0, OrigArg0.get());
  5213. TheCall->setArg(1, OrigArg1.get());
  5214. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5215. return false;
  5216. // If the common type isn't a real floating type, then the arguments were
  5217. // invalid for this operation.
  5218. if (Res.isNull() || !Res->isRealFloatingType())
  5219. return Diag(OrigArg0.get()->getBeginLoc(),
  5220. diag::err_typecheck_call_invalid_ordered_compare)
  5221. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5222. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5223. OrigArg1.get()->getEndLoc());
  5224. return false;
  5225. }
  5226. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5227. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5228. /// to check everything. We expect the last argument to be a floating point
  5229. /// value.
  5230. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5231. if (TheCall->getNumArgs() < NumArgs)
  5232. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5233. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5234. if (TheCall->getNumArgs() > NumArgs)
  5235. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5236. diag::err_typecheck_call_too_many_args)
  5237. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5238. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5239. (*(TheCall->arg_end() - 1))->getEndLoc());
  5240. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5241. if (OrigArg->isTypeDependent())
  5242. return false;
  5243. // This operation requires a non-_Complex floating-point number.
  5244. if (!OrigArg->getType()->isRealFloatingType())
  5245. return Diag(OrigArg->getBeginLoc(),
  5246. diag::err_typecheck_call_invalid_unary_fp)
  5247. << OrigArg->getType() << OrigArg->getSourceRange();
  5248. // If this is an implicit conversion from float -> float, double, or
  5249. // long double, remove it.
  5250. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5251. // Only remove standard FloatCasts, leaving other casts inplace
  5252. if (Cast->getCastKind() == CK_FloatingCast) {
  5253. Expr *CastArg = Cast->getSubExpr();
  5254. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5255. assert(
  5256. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5257. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5258. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5259. "promotion from float to either float, double, or long double is "
  5260. "the only expected cast here");
  5261. Cast->setSubExpr(nullptr);
  5262. TheCall->setArg(NumArgs-1, CastArg);
  5263. }
  5264. }
  5265. }
  5266. return false;
  5267. }
  5268. // Customized Sema Checking for VSX builtins that have the following signature:
  5269. // vector [...] builtinName(vector [...], vector [...], const int);
  5270. // Which takes the same type of vectors (any legal vector type) for the first
  5271. // two arguments and takes compile time constant for the third argument.
  5272. // Example builtins are :
  5273. // vector double vec_xxpermdi(vector double, vector double, int);
  5274. // vector short vec_xxsldwi(vector short, vector short, int);
  5275. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5276. unsigned ExpectedNumArgs = 3;
  5277. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5278. return Diag(TheCall->getEndLoc(),
  5279. diag::err_typecheck_call_too_few_args_at_least)
  5280. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5281. << TheCall->getSourceRange();
  5282. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5283. return Diag(TheCall->getEndLoc(),
  5284. diag::err_typecheck_call_too_many_args_at_most)
  5285. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5286. << TheCall->getSourceRange();
  5287. // Check the third argument is a compile time constant
  5288. llvm::APSInt Value;
  5289. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5290. return Diag(TheCall->getBeginLoc(),
  5291. diag::err_vsx_builtin_nonconstant_argument)
  5292. << 3 /* argument index */ << TheCall->getDirectCallee()
  5293. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5294. TheCall->getArg(2)->getEndLoc());
  5295. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5296. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5297. // Check the type of argument 1 and argument 2 are vectors.
  5298. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5299. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5300. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5301. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5302. << TheCall->getDirectCallee()
  5303. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5304. TheCall->getArg(1)->getEndLoc());
  5305. }
  5306. // Check the first two arguments are the same type.
  5307. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5308. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5309. << TheCall->getDirectCallee()
  5310. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5311. TheCall->getArg(1)->getEndLoc());
  5312. }
  5313. // When default clang type checking is turned off and the customized type
  5314. // checking is used, the returning type of the function must be explicitly
  5315. // set. Otherwise it is _Bool by default.
  5316. TheCall->setType(Arg1Ty);
  5317. return false;
  5318. }
  5319. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5320. // This is declared to take (...), so we have to check everything.
  5321. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5322. if (TheCall->getNumArgs() < 2)
  5323. return ExprError(Diag(TheCall->getEndLoc(),
  5324. diag::err_typecheck_call_too_few_args_at_least)
  5325. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5326. << TheCall->getSourceRange());
  5327. // Determine which of the following types of shufflevector we're checking:
  5328. // 1) unary, vector mask: (lhs, mask)
  5329. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5330. QualType resType = TheCall->getArg(0)->getType();
  5331. unsigned numElements = 0;
  5332. if (!TheCall->getArg(0)->isTypeDependent() &&
  5333. !TheCall->getArg(1)->isTypeDependent()) {
  5334. QualType LHSType = TheCall->getArg(0)->getType();
  5335. QualType RHSType = TheCall->getArg(1)->getType();
  5336. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5337. return ExprError(
  5338. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5339. << TheCall->getDirectCallee()
  5340. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5341. TheCall->getArg(1)->getEndLoc()));
  5342. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5343. unsigned numResElements = TheCall->getNumArgs() - 2;
  5344. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5345. // with mask. If so, verify that RHS is an integer vector type with the
  5346. // same number of elts as lhs.
  5347. if (TheCall->getNumArgs() == 2) {
  5348. if (!RHSType->hasIntegerRepresentation() ||
  5349. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5350. return ExprError(Diag(TheCall->getBeginLoc(),
  5351. diag::err_vec_builtin_incompatible_vector)
  5352. << TheCall->getDirectCallee()
  5353. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5354. TheCall->getArg(1)->getEndLoc()));
  5355. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5356. return ExprError(Diag(TheCall->getBeginLoc(),
  5357. diag::err_vec_builtin_incompatible_vector)
  5358. << TheCall->getDirectCallee()
  5359. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5360. TheCall->getArg(1)->getEndLoc()));
  5361. } else if (numElements != numResElements) {
  5362. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5363. resType = Context.getVectorType(eltType, numResElements,
  5364. VectorType::GenericVector);
  5365. }
  5366. }
  5367. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5368. if (TheCall->getArg(i)->isTypeDependent() ||
  5369. TheCall->getArg(i)->isValueDependent())
  5370. continue;
  5371. llvm::APSInt Result(32);
  5372. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5373. return ExprError(Diag(TheCall->getBeginLoc(),
  5374. diag::err_shufflevector_nonconstant_argument)
  5375. << TheCall->getArg(i)->getSourceRange());
  5376. // Allow -1 which will be translated to undef in the IR.
  5377. if (Result.isSigned() && Result.isAllOnesValue())
  5378. continue;
  5379. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5380. return ExprError(Diag(TheCall->getBeginLoc(),
  5381. diag::err_shufflevector_argument_too_large)
  5382. << TheCall->getArg(i)->getSourceRange());
  5383. }
  5384. SmallVector<Expr*, 32> exprs;
  5385. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5386. exprs.push_back(TheCall->getArg(i));
  5387. TheCall->setArg(i, nullptr);
  5388. }
  5389. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5390. TheCall->getCallee()->getBeginLoc(),
  5391. TheCall->getRParenLoc());
  5392. }
  5393. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5394. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5395. SourceLocation BuiltinLoc,
  5396. SourceLocation RParenLoc) {
  5397. ExprValueKind VK = VK_RValue;
  5398. ExprObjectKind OK = OK_Ordinary;
  5399. QualType DstTy = TInfo->getType();
  5400. QualType SrcTy = E->getType();
  5401. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5402. return ExprError(Diag(BuiltinLoc,
  5403. diag::err_convertvector_non_vector)
  5404. << E->getSourceRange());
  5405. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5406. return ExprError(Diag(BuiltinLoc,
  5407. diag::err_convertvector_non_vector_type));
  5408. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5409. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5410. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5411. if (SrcElts != DstElts)
  5412. return ExprError(Diag(BuiltinLoc,
  5413. diag::err_convertvector_incompatible_vector)
  5414. << E->getSourceRange());
  5415. }
  5416. return new (Context)
  5417. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5418. }
  5419. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5420. // This is declared to take (const void*, ...) and can take two
  5421. // optional constant int args.
  5422. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5423. unsigned NumArgs = TheCall->getNumArgs();
  5424. if (NumArgs > 3)
  5425. return Diag(TheCall->getEndLoc(),
  5426. diag::err_typecheck_call_too_many_args_at_most)
  5427. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5428. // Argument 0 is checked for us and the remaining arguments must be
  5429. // constant integers.
  5430. for (unsigned i = 1; i != NumArgs; ++i)
  5431. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5432. return true;
  5433. return false;
  5434. }
  5435. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5436. // __assume does not evaluate its arguments, and should warn if its argument
  5437. // has side effects.
  5438. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5439. Expr *Arg = TheCall->getArg(0);
  5440. if (Arg->isInstantiationDependent()) return false;
  5441. if (Arg->HasSideEffects(Context))
  5442. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5443. << Arg->getSourceRange()
  5444. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5445. return false;
  5446. }
  5447. /// Handle __builtin_alloca_with_align. This is declared
  5448. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5449. /// than 8.
  5450. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5451. // The alignment must be a constant integer.
  5452. Expr *Arg = TheCall->getArg(1);
  5453. // We can't check the value of a dependent argument.
  5454. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5455. if (const auto *UE =
  5456. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5457. if (UE->getKind() == UETT_AlignOf ||
  5458. UE->getKind() == UETT_PreferredAlignOf)
  5459. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5460. << Arg->getSourceRange();
  5461. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5462. if (!Result.isPowerOf2())
  5463. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5464. << Arg->getSourceRange();
  5465. if (Result < Context.getCharWidth())
  5466. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5467. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5468. if (Result > std::numeric_limits<int32_t>::max())
  5469. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5470. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5471. }
  5472. return false;
  5473. }
  5474. /// Handle __builtin_assume_aligned. This is declared
  5475. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5476. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5477. unsigned NumArgs = TheCall->getNumArgs();
  5478. if (NumArgs > 3)
  5479. return Diag(TheCall->getEndLoc(),
  5480. diag::err_typecheck_call_too_many_args_at_most)
  5481. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5482. // The alignment must be a constant integer.
  5483. Expr *Arg = TheCall->getArg(1);
  5484. // We can't check the value of a dependent argument.
  5485. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5486. llvm::APSInt Result;
  5487. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5488. return true;
  5489. if (!Result.isPowerOf2())
  5490. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5491. << Arg->getSourceRange();
  5492. }
  5493. if (NumArgs > 2) {
  5494. ExprResult Arg(TheCall->getArg(2));
  5495. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5496. Context.getSizeType(), false);
  5497. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5498. if (Arg.isInvalid()) return true;
  5499. TheCall->setArg(2, Arg.get());
  5500. }
  5501. return false;
  5502. }
  5503. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5504. unsigned BuiltinID =
  5505. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5506. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5507. unsigned NumArgs = TheCall->getNumArgs();
  5508. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5509. if (NumArgs < NumRequiredArgs) {
  5510. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5511. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5512. << TheCall->getSourceRange();
  5513. }
  5514. if (NumArgs >= NumRequiredArgs + 0x100) {
  5515. return Diag(TheCall->getEndLoc(),
  5516. diag::err_typecheck_call_too_many_args_at_most)
  5517. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5518. << TheCall->getSourceRange();
  5519. }
  5520. unsigned i = 0;
  5521. // For formatting call, check buffer arg.
  5522. if (!IsSizeCall) {
  5523. ExprResult Arg(TheCall->getArg(i));
  5524. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5525. Context, Context.VoidPtrTy, false);
  5526. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5527. if (Arg.isInvalid())
  5528. return true;
  5529. TheCall->setArg(i, Arg.get());
  5530. i++;
  5531. }
  5532. // Check string literal arg.
  5533. unsigned FormatIdx = i;
  5534. {
  5535. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5536. if (Arg.isInvalid())
  5537. return true;
  5538. TheCall->setArg(i, Arg.get());
  5539. i++;
  5540. }
  5541. // Make sure variadic args are scalar.
  5542. unsigned FirstDataArg = i;
  5543. while (i < NumArgs) {
  5544. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5545. TheCall->getArg(i), VariadicFunction, nullptr);
  5546. if (Arg.isInvalid())
  5547. return true;
  5548. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5549. if (ArgSize.getQuantity() >= 0x100) {
  5550. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5551. << i << (int)ArgSize.getQuantity() << 0xff
  5552. << TheCall->getSourceRange();
  5553. }
  5554. TheCall->setArg(i, Arg.get());
  5555. i++;
  5556. }
  5557. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5558. // call to avoid duplicate diagnostics.
  5559. if (!IsSizeCall) {
  5560. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5561. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5562. bool Success = CheckFormatArguments(
  5563. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5564. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5565. CheckedVarArgs);
  5566. if (!Success)
  5567. return true;
  5568. }
  5569. if (IsSizeCall) {
  5570. TheCall->setType(Context.getSizeType());
  5571. } else {
  5572. TheCall->setType(Context.VoidPtrTy);
  5573. }
  5574. return false;
  5575. }
  5576. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5577. /// TheCall is a constant expression.
  5578. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5579. llvm::APSInt &Result) {
  5580. Expr *Arg = TheCall->getArg(ArgNum);
  5581. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5582. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5583. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5584. if (!Arg->isIntegerConstantExpr(Result, Context))
  5585. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5586. << FDecl->getDeclName() << Arg->getSourceRange();
  5587. return false;
  5588. }
  5589. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5590. /// TheCall is a constant expression in the range [Low, High].
  5591. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5592. int Low, int High, bool RangeIsError) {
  5593. if (isConstantEvaluated())
  5594. return false;
  5595. llvm::APSInt Result;
  5596. // We can't check the value of a dependent argument.
  5597. Expr *Arg = TheCall->getArg(ArgNum);
  5598. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5599. return false;
  5600. // Check constant-ness first.
  5601. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5602. return true;
  5603. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5604. if (RangeIsError)
  5605. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5606. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5607. else
  5608. // Defer the warning until we know if the code will be emitted so that
  5609. // dead code can ignore this.
  5610. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5611. PDiag(diag::warn_argument_invalid_range)
  5612. << Result.toString(10) << Low << High
  5613. << Arg->getSourceRange());
  5614. }
  5615. return false;
  5616. }
  5617. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5618. /// TheCall is a constant expression is a multiple of Num..
  5619. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5620. unsigned Num) {
  5621. llvm::APSInt Result;
  5622. // We can't check the value of a dependent argument.
  5623. Expr *Arg = TheCall->getArg(ArgNum);
  5624. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5625. return false;
  5626. // Check constant-ness first.
  5627. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5628. return true;
  5629. if (Result.getSExtValue() % Num != 0)
  5630. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5631. << Num << Arg->getSourceRange();
  5632. return false;
  5633. }
  5634. /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
  5635. bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
  5636. if (BuiltinID == AArch64::BI__builtin_arm_irg) {
  5637. if (checkArgCount(*this, TheCall, 2))
  5638. return true;
  5639. Expr *Arg0 = TheCall->getArg(0);
  5640. Expr *Arg1 = TheCall->getArg(1);
  5641. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5642. if (FirstArg.isInvalid())
  5643. return true;
  5644. QualType FirstArgType = FirstArg.get()->getType();
  5645. if (!FirstArgType->isAnyPointerType())
  5646. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5647. << "first" << FirstArgType << Arg0->getSourceRange();
  5648. TheCall->setArg(0, FirstArg.get());
  5649. ExprResult SecArg = DefaultLvalueConversion(Arg1);
  5650. if (SecArg.isInvalid())
  5651. return true;
  5652. QualType SecArgType = SecArg.get()->getType();
  5653. if (!SecArgType->isIntegerType())
  5654. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5655. << "second" << SecArgType << Arg1->getSourceRange();
  5656. // Derive the return type from the pointer argument.
  5657. TheCall->setType(FirstArgType);
  5658. return false;
  5659. }
  5660. if (BuiltinID == AArch64::BI__builtin_arm_addg) {
  5661. if (checkArgCount(*this, TheCall, 2))
  5662. return true;
  5663. Expr *Arg0 = TheCall->getArg(0);
  5664. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5665. if (FirstArg.isInvalid())
  5666. return true;
  5667. QualType FirstArgType = FirstArg.get()->getType();
  5668. if (!FirstArgType->isAnyPointerType())
  5669. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5670. << "first" << FirstArgType << Arg0->getSourceRange();
  5671. TheCall->setArg(0, FirstArg.get());
  5672. // Derive the return type from the pointer argument.
  5673. TheCall->setType(FirstArgType);
  5674. // Second arg must be an constant in range [0,15]
  5675. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5676. }
  5677. if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
  5678. if (checkArgCount(*this, TheCall, 2))
  5679. return true;
  5680. Expr *Arg0 = TheCall->getArg(0);
  5681. Expr *Arg1 = TheCall->getArg(1);
  5682. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5683. if (FirstArg.isInvalid())
  5684. return true;
  5685. QualType FirstArgType = FirstArg.get()->getType();
  5686. if (!FirstArgType->isAnyPointerType())
  5687. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5688. << "first" << FirstArgType << Arg0->getSourceRange();
  5689. QualType SecArgType = Arg1->getType();
  5690. if (!SecArgType->isIntegerType())
  5691. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
  5692. << "second" << SecArgType << Arg1->getSourceRange();
  5693. TheCall->setType(Context.IntTy);
  5694. return false;
  5695. }
  5696. if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
  5697. BuiltinID == AArch64::BI__builtin_arm_stg) {
  5698. if (checkArgCount(*this, TheCall, 1))
  5699. return true;
  5700. Expr *Arg0 = TheCall->getArg(0);
  5701. ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
  5702. if (FirstArg.isInvalid())
  5703. return true;
  5704. QualType FirstArgType = FirstArg.get()->getType();
  5705. if (!FirstArgType->isAnyPointerType())
  5706. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
  5707. << "first" << FirstArgType << Arg0->getSourceRange();
  5708. TheCall->setArg(0, FirstArg.get());
  5709. // Derive the return type from the pointer argument.
  5710. if (BuiltinID == AArch64::BI__builtin_arm_ldg)
  5711. TheCall->setType(FirstArgType);
  5712. return false;
  5713. }
  5714. if (BuiltinID == AArch64::BI__builtin_arm_subp) {
  5715. Expr *ArgA = TheCall->getArg(0);
  5716. Expr *ArgB = TheCall->getArg(1);
  5717. ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
  5718. ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
  5719. if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
  5720. return true;
  5721. QualType ArgTypeA = ArgExprA.get()->getType();
  5722. QualType ArgTypeB = ArgExprB.get()->getType();
  5723. auto isNull = [&] (Expr *E) -> bool {
  5724. return E->isNullPointerConstant(
  5725. Context, Expr::NPC_ValueDependentIsNotNull); };
  5726. // argument should be either a pointer or null
  5727. if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
  5728. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5729. << "first" << ArgTypeA << ArgA->getSourceRange();
  5730. if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
  5731. return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
  5732. << "second" << ArgTypeB << ArgB->getSourceRange();
  5733. // Ensure Pointee types are compatible
  5734. if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
  5735. ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
  5736. QualType pointeeA = ArgTypeA->getPointeeType();
  5737. QualType pointeeB = ArgTypeB->getPointeeType();
  5738. if (!Context.typesAreCompatible(
  5739. Context.getCanonicalType(pointeeA).getUnqualifiedType(),
  5740. Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
  5741. return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
  5742. << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
  5743. << ArgB->getSourceRange();
  5744. }
  5745. }
  5746. // at least one argument should be pointer type
  5747. if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
  5748. return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
  5749. << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
  5750. if (isNull(ArgA)) // adopt type of the other pointer
  5751. ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
  5752. if (isNull(ArgB))
  5753. ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
  5754. TheCall->setArg(0, ArgExprA.get());
  5755. TheCall->setArg(1, ArgExprB.get());
  5756. TheCall->setType(Context.LongLongTy);
  5757. return false;
  5758. }
  5759. assert(false && "Unhandled ARM MTE intrinsic");
  5760. return true;
  5761. }
  5762. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5763. /// TheCall is an ARM/AArch64 special register string literal.
  5764. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5765. int ArgNum, unsigned ExpectedFieldNum,
  5766. bool AllowName) {
  5767. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5768. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5769. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5770. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5771. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5772. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5773. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5774. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5775. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5776. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5777. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5778. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5779. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5780. // We can't check the value of a dependent argument.
  5781. Expr *Arg = TheCall->getArg(ArgNum);
  5782. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5783. return false;
  5784. // Check if the argument is a string literal.
  5785. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5786. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5787. << Arg->getSourceRange();
  5788. // Check the type of special register given.
  5789. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5790. SmallVector<StringRef, 6> Fields;
  5791. Reg.split(Fields, ":");
  5792. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5793. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5794. << Arg->getSourceRange();
  5795. // If the string is the name of a register then we cannot check that it is
  5796. // valid here but if the string is of one the forms described in ACLE then we
  5797. // can check that the supplied fields are integers and within the valid
  5798. // ranges.
  5799. if (Fields.size() > 1) {
  5800. bool FiveFields = Fields.size() == 5;
  5801. bool ValidString = true;
  5802. if (IsARMBuiltin) {
  5803. ValidString &= Fields[0].startswith_lower("cp") ||
  5804. Fields[0].startswith_lower("p");
  5805. if (ValidString)
  5806. Fields[0] =
  5807. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5808. ValidString &= Fields[2].startswith_lower("c");
  5809. if (ValidString)
  5810. Fields[2] = Fields[2].drop_front(1);
  5811. if (FiveFields) {
  5812. ValidString &= Fields[3].startswith_lower("c");
  5813. if (ValidString)
  5814. Fields[3] = Fields[3].drop_front(1);
  5815. }
  5816. }
  5817. SmallVector<int, 5> Ranges;
  5818. if (FiveFields)
  5819. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5820. else
  5821. Ranges.append({15, 7, 15});
  5822. for (unsigned i=0; i<Fields.size(); ++i) {
  5823. int IntField;
  5824. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5825. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5826. }
  5827. if (!ValidString)
  5828. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5829. << Arg->getSourceRange();
  5830. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5831. // If the register name is one of those that appear in the condition below
  5832. // and the special register builtin being used is one of the write builtins,
  5833. // then we require that the argument provided for writing to the register
  5834. // is an integer constant expression. This is because it will be lowered to
  5835. // an MSR (immediate) instruction, so we need to know the immediate at
  5836. // compile time.
  5837. if (TheCall->getNumArgs() != 2)
  5838. return false;
  5839. std::string RegLower = Reg.lower();
  5840. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5841. RegLower != "pan" && RegLower != "uao")
  5842. return false;
  5843. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5844. }
  5845. return false;
  5846. }
  5847. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5848. /// This checks that the target supports __builtin_longjmp and
  5849. /// that val is a constant 1.
  5850. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5851. if (!Context.getTargetInfo().hasSjLjLowering())
  5852. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5853. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5854. Expr *Arg = TheCall->getArg(1);
  5855. llvm::APSInt Result;
  5856. // TODO: This is less than ideal. Overload this to take a value.
  5857. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5858. return true;
  5859. if (Result != 1)
  5860. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5861. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5862. return false;
  5863. }
  5864. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5865. /// This checks that the target supports __builtin_setjmp.
  5866. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5867. if (!Context.getTargetInfo().hasSjLjLowering())
  5868. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5869. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5870. return false;
  5871. }
  5872. namespace {
  5873. class UncoveredArgHandler {
  5874. enum { Unknown = -1, AllCovered = -2 };
  5875. signed FirstUncoveredArg = Unknown;
  5876. SmallVector<const Expr *, 4> DiagnosticExprs;
  5877. public:
  5878. UncoveredArgHandler() = default;
  5879. bool hasUncoveredArg() const {
  5880. return (FirstUncoveredArg >= 0);
  5881. }
  5882. unsigned getUncoveredArg() const {
  5883. assert(hasUncoveredArg() && "no uncovered argument");
  5884. return FirstUncoveredArg;
  5885. }
  5886. void setAllCovered() {
  5887. // A string has been found with all arguments covered, so clear out
  5888. // the diagnostics.
  5889. DiagnosticExprs.clear();
  5890. FirstUncoveredArg = AllCovered;
  5891. }
  5892. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5893. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5894. // Don't update if a previous string covers all arguments.
  5895. if (FirstUncoveredArg == AllCovered)
  5896. return;
  5897. // UncoveredArgHandler tracks the highest uncovered argument index
  5898. // and with it all the strings that match this index.
  5899. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5900. DiagnosticExprs.push_back(StrExpr);
  5901. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5902. DiagnosticExprs.clear();
  5903. DiagnosticExprs.push_back(StrExpr);
  5904. FirstUncoveredArg = NewFirstUncoveredArg;
  5905. }
  5906. }
  5907. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5908. };
  5909. enum StringLiteralCheckType {
  5910. SLCT_NotALiteral,
  5911. SLCT_UncheckedLiteral,
  5912. SLCT_CheckedLiteral
  5913. };
  5914. } // namespace
  5915. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5916. BinaryOperatorKind BinOpKind,
  5917. bool AddendIsRight) {
  5918. unsigned BitWidth = Offset.getBitWidth();
  5919. unsigned AddendBitWidth = Addend.getBitWidth();
  5920. // There might be negative interim results.
  5921. if (Addend.isUnsigned()) {
  5922. Addend = Addend.zext(++AddendBitWidth);
  5923. Addend.setIsSigned(true);
  5924. }
  5925. // Adjust the bit width of the APSInts.
  5926. if (AddendBitWidth > BitWidth) {
  5927. Offset = Offset.sext(AddendBitWidth);
  5928. BitWidth = AddendBitWidth;
  5929. } else if (BitWidth > AddendBitWidth) {
  5930. Addend = Addend.sext(BitWidth);
  5931. }
  5932. bool Ov = false;
  5933. llvm::APSInt ResOffset = Offset;
  5934. if (BinOpKind == BO_Add)
  5935. ResOffset = Offset.sadd_ov(Addend, Ov);
  5936. else {
  5937. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5938. "operator must be add or sub with addend on the right");
  5939. ResOffset = Offset.ssub_ov(Addend, Ov);
  5940. }
  5941. // We add an offset to a pointer here so we should support an offset as big as
  5942. // possible.
  5943. if (Ov) {
  5944. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5945. "index (intermediate) result too big");
  5946. Offset = Offset.sext(2 * BitWidth);
  5947. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5948. return;
  5949. }
  5950. Offset = ResOffset;
  5951. }
  5952. namespace {
  5953. // This is a wrapper class around StringLiteral to support offsetted string
  5954. // literals as format strings. It takes the offset into account when returning
  5955. // the string and its length or the source locations to display notes correctly.
  5956. class FormatStringLiteral {
  5957. const StringLiteral *FExpr;
  5958. int64_t Offset;
  5959. public:
  5960. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5961. : FExpr(fexpr), Offset(Offset) {}
  5962. StringRef getString() const {
  5963. return FExpr->getString().drop_front(Offset);
  5964. }
  5965. unsigned getByteLength() const {
  5966. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5967. }
  5968. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5969. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5970. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5971. QualType getType() const { return FExpr->getType(); }
  5972. bool isAscii() const { return FExpr->isAscii(); }
  5973. bool isWide() const { return FExpr->isWide(); }
  5974. bool isUTF8() const { return FExpr->isUTF8(); }
  5975. bool isUTF16() const { return FExpr->isUTF16(); }
  5976. bool isUTF32() const { return FExpr->isUTF32(); }
  5977. bool isPascal() const { return FExpr->isPascal(); }
  5978. SourceLocation getLocationOfByte(
  5979. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5980. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5981. unsigned *StartTokenByteOffset = nullptr) const {
  5982. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5983. StartToken, StartTokenByteOffset);
  5984. }
  5985. SourceLocation getBeginLoc() const LLVM_READONLY {
  5986. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5987. }
  5988. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5989. };
  5990. } // namespace
  5991. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5992. const Expr *OrigFormatExpr,
  5993. ArrayRef<const Expr *> Args,
  5994. bool HasVAListArg, unsigned format_idx,
  5995. unsigned firstDataArg,
  5996. Sema::FormatStringType Type,
  5997. bool inFunctionCall,
  5998. Sema::VariadicCallType CallType,
  5999. llvm::SmallBitVector &CheckedVarArgs,
  6000. UncoveredArgHandler &UncoveredArg);
  6001. // Determine if an expression is a string literal or constant string.
  6002. // If this function returns false on the arguments to a function expecting a
  6003. // format string, we will usually need to emit a warning.
  6004. // True string literals are then checked by CheckFormatString.
  6005. static StringLiteralCheckType
  6006. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  6007. bool HasVAListArg, unsigned format_idx,
  6008. unsigned firstDataArg, Sema::FormatStringType Type,
  6009. Sema::VariadicCallType CallType, bool InFunctionCall,
  6010. llvm::SmallBitVector &CheckedVarArgs,
  6011. UncoveredArgHandler &UncoveredArg,
  6012. llvm::APSInt Offset) {
  6013. if (S.isConstantEvaluated())
  6014. return SLCT_NotALiteral;
  6015. tryAgain:
  6016. assert(Offset.isSigned() && "invalid offset");
  6017. if (E->isTypeDependent() || E->isValueDependent())
  6018. return SLCT_NotALiteral;
  6019. E = E->IgnoreParenCasts();
  6020. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  6021. // Technically -Wformat-nonliteral does not warn about this case.
  6022. // The behavior of printf and friends in this case is implementation
  6023. // dependent. Ideally if the format string cannot be null then
  6024. // it should have a 'nonnull' attribute in the function prototype.
  6025. return SLCT_UncheckedLiteral;
  6026. switch (E->getStmtClass()) {
  6027. case Stmt::BinaryConditionalOperatorClass:
  6028. case Stmt::ConditionalOperatorClass: {
  6029. // The expression is a literal if both sub-expressions were, and it was
  6030. // completely checked only if both sub-expressions were checked.
  6031. const AbstractConditionalOperator *C =
  6032. cast<AbstractConditionalOperator>(E);
  6033. // Determine whether it is necessary to check both sub-expressions, for
  6034. // example, because the condition expression is a constant that can be
  6035. // evaluated at compile time.
  6036. bool CheckLeft = true, CheckRight = true;
  6037. bool Cond;
  6038. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
  6039. S.isConstantEvaluated())) {
  6040. if (Cond)
  6041. CheckRight = false;
  6042. else
  6043. CheckLeft = false;
  6044. }
  6045. // We need to maintain the offsets for the right and the left hand side
  6046. // separately to check if every possible indexed expression is a valid
  6047. // string literal. They might have different offsets for different string
  6048. // literals in the end.
  6049. StringLiteralCheckType Left;
  6050. if (!CheckLeft)
  6051. Left = SLCT_UncheckedLiteral;
  6052. else {
  6053. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  6054. HasVAListArg, format_idx, firstDataArg,
  6055. Type, CallType, InFunctionCall,
  6056. CheckedVarArgs, UncoveredArg, Offset);
  6057. if (Left == SLCT_NotALiteral || !CheckRight) {
  6058. return Left;
  6059. }
  6060. }
  6061. StringLiteralCheckType Right =
  6062. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  6063. HasVAListArg, format_idx, firstDataArg,
  6064. Type, CallType, InFunctionCall, CheckedVarArgs,
  6065. UncoveredArg, Offset);
  6066. return (CheckLeft && Left < Right) ? Left : Right;
  6067. }
  6068. case Stmt::ImplicitCastExprClass:
  6069. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  6070. goto tryAgain;
  6071. case Stmt::OpaqueValueExprClass:
  6072. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  6073. E = src;
  6074. goto tryAgain;
  6075. }
  6076. return SLCT_NotALiteral;
  6077. case Stmt::PredefinedExprClass:
  6078. // While __func__, etc., are technically not string literals, they
  6079. // cannot contain format specifiers and thus are not a security
  6080. // liability.
  6081. return SLCT_UncheckedLiteral;
  6082. case Stmt::DeclRefExprClass: {
  6083. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6084. // As an exception, do not flag errors for variables binding to
  6085. // const string literals.
  6086. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  6087. bool isConstant = false;
  6088. QualType T = DR->getType();
  6089. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  6090. isConstant = AT->getElementType().isConstant(S.Context);
  6091. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  6092. isConstant = T.isConstant(S.Context) &&
  6093. PT->getPointeeType().isConstant(S.Context);
  6094. } else if (T->isObjCObjectPointerType()) {
  6095. // In ObjC, there is usually no "const ObjectPointer" type,
  6096. // so don't check if the pointee type is constant.
  6097. isConstant = T.isConstant(S.Context);
  6098. }
  6099. if (isConstant) {
  6100. if (const Expr *Init = VD->getAnyInitializer()) {
  6101. // Look through initializers like const char c[] = { "foo" }
  6102. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  6103. if (InitList->isStringLiteralInit())
  6104. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  6105. }
  6106. return checkFormatStringExpr(S, Init, Args,
  6107. HasVAListArg, format_idx,
  6108. firstDataArg, Type, CallType,
  6109. /*InFunctionCall*/ false, CheckedVarArgs,
  6110. UncoveredArg, Offset);
  6111. }
  6112. }
  6113. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  6114. // special check to see if the format string is a function parameter
  6115. // of the function calling the printf function. If the function
  6116. // has an attribute indicating it is a printf-like function, then we
  6117. // should suppress warnings concerning non-literals being used in a call
  6118. // to a vprintf function. For example:
  6119. //
  6120. // void
  6121. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  6122. // va_list ap;
  6123. // va_start(ap, fmt);
  6124. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  6125. // ...
  6126. // }
  6127. if (HasVAListArg) {
  6128. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  6129. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  6130. int PVIndex = PV->getFunctionScopeIndex() + 1;
  6131. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  6132. // adjust for implicit parameter
  6133. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6134. if (MD->isInstance())
  6135. ++PVIndex;
  6136. // We also check if the formats are compatible.
  6137. // We can't pass a 'scanf' string to a 'printf' function.
  6138. if (PVIndex == PVFormat->getFormatIdx() &&
  6139. Type == S.GetFormatStringType(PVFormat))
  6140. return SLCT_UncheckedLiteral;
  6141. }
  6142. }
  6143. }
  6144. }
  6145. }
  6146. return SLCT_NotALiteral;
  6147. }
  6148. case Stmt::CallExprClass:
  6149. case Stmt::CXXMemberCallExprClass: {
  6150. const CallExpr *CE = cast<CallExpr>(E);
  6151. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  6152. bool IsFirst = true;
  6153. StringLiteralCheckType CommonResult;
  6154. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  6155. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  6156. StringLiteralCheckType Result = checkFormatStringExpr(
  6157. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6158. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6159. if (IsFirst) {
  6160. CommonResult = Result;
  6161. IsFirst = false;
  6162. }
  6163. }
  6164. if (!IsFirst)
  6165. return CommonResult;
  6166. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6167. unsigned BuiltinID = FD->getBuiltinID();
  6168. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  6169. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  6170. const Expr *Arg = CE->getArg(0);
  6171. return checkFormatStringExpr(S, Arg, Args,
  6172. HasVAListArg, format_idx,
  6173. firstDataArg, Type, CallType,
  6174. InFunctionCall, CheckedVarArgs,
  6175. UncoveredArg, Offset);
  6176. }
  6177. }
  6178. }
  6179. return SLCT_NotALiteral;
  6180. }
  6181. case Stmt::ObjCMessageExprClass: {
  6182. const auto *ME = cast<ObjCMessageExpr>(E);
  6183. if (const auto *ND = ME->getMethodDecl()) {
  6184. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  6185. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  6186. return checkFormatStringExpr(
  6187. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  6188. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  6189. }
  6190. }
  6191. return SLCT_NotALiteral;
  6192. }
  6193. case Stmt::ObjCStringLiteralClass:
  6194. case Stmt::StringLiteralClass: {
  6195. const StringLiteral *StrE = nullptr;
  6196. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  6197. StrE = ObjCFExpr->getString();
  6198. else
  6199. StrE = cast<StringLiteral>(E);
  6200. if (StrE) {
  6201. if (Offset.isNegative() || Offset > StrE->getLength()) {
  6202. // TODO: It would be better to have an explicit warning for out of
  6203. // bounds literals.
  6204. return SLCT_NotALiteral;
  6205. }
  6206. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  6207. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  6208. firstDataArg, Type, InFunctionCall, CallType,
  6209. CheckedVarArgs, UncoveredArg);
  6210. return SLCT_CheckedLiteral;
  6211. }
  6212. return SLCT_NotALiteral;
  6213. }
  6214. case Stmt::BinaryOperatorClass: {
  6215. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  6216. // A string literal + an int offset is still a string literal.
  6217. if (BinOp->isAdditiveOp()) {
  6218. Expr::EvalResult LResult, RResult;
  6219. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
  6220. LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6221. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
  6222. RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
  6223. if (LIsInt != RIsInt) {
  6224. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6225. if (LIsInt) {
  6226. if (BinOpKind == BO_Add) {
  6227. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6228. E = BinOp->getRHS();
  6229. goto tryAgain;
  6230. }
  6231. } else {
  6232. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6233. E = BinOp->getLHS();
  6234. goto tryAgain;
  6235. }
  6236. }
  6237. }
  6238. return SLCT_NotALiteral;
  6239. }
  6240. case Stmt::UnaryOperatorClass: {
  6241. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6242. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6243. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6244. Expr::EvalResult IndexResult;
  6245. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
  6246. Expr::SE_NoSideEffects,
  6247. S.isConstantEvaluated())) {
  6248. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6249. /*RHS is int*/ true);
  6250. E = ASE->getBase();
  6251. goto tryAgain;
  6252. }
  6253. }
  6254. return SLCT_NotALiteral;
  6255. }
  6256. default:
  6257. return SLCT_NotALiteral;
  6258. }
  6259. }
  6260. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6261. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6262. .Case("scanf", FST_Scanf)
  6263. .Cases("printf", "printf0", FST_Printf)
  6264. .Cases("NSString", "CFString", FST_NSString)
  6265. .Case("strftime", FST_Strftime)
  6266. .Case("strfmon", FST_Strfmon)
  6267. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6268. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6269. .Case("os_trace", FST_OSLog)
  6270. .Case("os_log", FST_OSLog)
  6271. .Default(FST_Unknown);
  6272. }
  6273. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6274. /// functions) for correct use of format strings.
  6275. /// Returns true if a format string has been fully checked.
  6276. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6277. ArrayRef<const Expr *> Args,
  6278. bool IsCXXMember,
  6279. VariadicCallType CallType,
  6280. SourceLocation Loc, SourceRange Range,
  6281. llvm::SmallBitVector &CheckedVarArgs) {
  6282. FormatStringInfo FSI;
  6283. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6284. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6285. FSI.FirstDataArg, GetFormatStringType(Format),
  6286. CallType, Loc, Range, CheckedVarArgs);
  6287. return false;
  6288. }
  6289. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6290. bool HasVAListArg, unsigned format_idx,
  6291. unsigned firstDataArg, FormatStringType Type,
  6292. VariadicCallType CallType,
  6293. SourceLocation Loc, SourceRange Range,
  6294. llvm::SmallBitVector &CheckedVarArgs) {
  6295. // CHECK: printf/scanf-like function is called with no format string.
  6296. if (format_idx >= Args.size()) {
  6297. Diag(Loc, diag::warn_missing_format_string) << Range;
  6298. return false;
  6299. }
  6300. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6301. // CHECK: format string is not a string literal.
  6302. //
  6303. // Dynamically generated format strings are difficult to
  6304. // automatically vet at compile time. Requiring that format strings
  6305. // are string literals: (1) permits the checking of format strings by
  6306. // the compiler and thereby (2) can practically remove the source of
  6307. // many format string exploits.
  6308. // Format string can be either ObjC string (e.g. @"%d") or
  6309. // C string (e.g. "%d")
  6310. // ObjC string uses the same format specifiers as C string, so we can use
  6311. // the same format string checking logic for both ObjC and C strings.
  6312. UncoveredArgHandler UncoveredArg;
  6313. StringLiteralCheckType CT =
  6314. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6315. format_idx, firstDataArg, Type, CallType,
  6316. /*IsFunctionCall*/ true, CheckedVarArgs,
  6317. UncoveredArg,
  6318. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6319. // Generate a diagnostic where an uncovered argument is detected.
  6320. if (UncoveredArg.hasUncoveredArg()) {
  6321. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6322. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6323. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6324. }
  6325. if (CT != SLCT_NotALiteral)
  6326. // Literal format string found, check done!
  6327. return CT == SLCT_CheckedLiteral;
  6328. // Strftime is particular as it always uses a single 'time' argument,
  6329. // so it is safe to pass a non-literal string.
  6330. if (Type == FST_Strftime)
  6331. return false;
  6332. // Do not emit diag when the string param is a macro expansion and the
  6333. // format is either NSString or CFString. This is a hack to prevent
  6334. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6335. // which are usually used in place of NS and CF string literals.
  6336. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6337. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6338. return false;
  6339. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6340. // warn only with -Wformat-nonliteral.
  6341. if (Args.size() == firstDataArg) {
  6342. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6343. << OrigFormatExpr->getSourceRange();
  6344. switch (Type) {
  6345. default:
  6346. break;
  6347. case FST_Kprintf:
  6348. case FST_FreeBSDKPrintf:
  6349. case FST_Printf:
  6350. Diag(FormatLoc, diag::note_format_security_fixit)
  6351. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6352. break;
  6353. case FST_NSString:
  6354. Diag(FormatLoc, diag::note_format_security_fixit)
  6355. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6356. break;
  6357. }
  6358. } else {
  6359. Diag(FormatLoc, diag::warn_format_nonliteral)
  6360. << OrigFormatExpr->getSourceRange();
  6361. }
  6362. return false;
  6363. }
  6364. namespace {
  6365. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6366. protected:
  6367. Sema &S;
  6368. const FormatStringLiteral *FExpr;
  6369. const Expr *OrigFormatExpr;
  6370. const Sema::FormatStringType FSType;
  6371. const unsigned FirstDataArg;
  6372. const unsigned NumDataArgs;
  6373. const char *Beg; // Start of format string.
  6374. const bool HasVAListArg;
  6375. ArrayRef<const Expr *> Args;
  6376. unsigned FormatIdx;
  6377. llvm::SmallBitVector CoveredArgs;
  6378. bool usesPositionalArgs = false;
  6379. bool atFirstArg = true;
  6380. bool inFunctionCall;
  6381. Sema::VariadicCallType CallType;
  6382. llvm::SmallBitVector &CheckedVarArgs;
  6383. UncoveredArgHandler &UncoveredArg;
  6384. public:
  6385. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6386. const Expr *origFormatExpr,
  6387. const Sema::FormatStringType type, unsigned firstDataArg,
  6388. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6389. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6390. bool inFunctionCall, Sema::VariadicCallType callType,
  6391. llvm::SmallBitVector &CheckedVarArgs,
  6392. UncoveredArgHandler &UncoveredArg)
  6393. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6394. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6395. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6396. inFunctionCall(inFunctionCall), CallType(callType),
  6397. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6398. CoveredArgs.resize(numDataArgs);
  6399. CoveredArgs.reset();
  6400. }
  6401. void DoneProcessing();
  6402. void HandleIncompleteSpecifier(const char *startSpecifier,
  6403. unsigned specifierLen) override;
  6404. void HandleInvalidLengthModifier(
  6405. const analyze_format_string::FormatSpecifier &FS,
  6406. const analyze_format_string::ConversionSpecifier &CS,
  6407. const char *startSpecifier, unsigned specifierLen,
  6408. unsigned DiagID);
  6409. void HandleNonStandardLengthModifier(
  6410. const analyze_format_string::FormatSpecifier &FS,
  6411. const char *startSpecifier, unsigned specifierLen);
  6412. void HandleNonStandardConversionSpecifier(
  6413. const analyze_format_string::ConversionSpecifier &CS,
  6414. const char *startSpecifier, unsigned specifierLen);
  6415. void HandlePosition(const char *startPos, unsigned posLen) override;
  6416. void HandleInvalidPosition(const char *startSpecifier,
  6417. unsigned specifierLen,
  6418. analyze_format_string::PositionContext p) override;
  6419. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6420. void HandleNullChar(const char *nullCharacter) override;
  6421. template <typename Range>
  6422. static void
  6423. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6424. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6425. bool IsStringLocation, Range StringRange,
  6426. ArrayRef<FixItHint> Fixit = None);
  6427. protected:
  6428. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6429. const char *startSpec,
  6430. unsigned specifierLen,
  6431. const char *csStart, unsigned csLen);
  6432. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6433. const char *startSpec,
  6434. unsigned specifierLen);
  6435. SourceRange getFormatStringRange();
  6436. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6437. unsigned specifierLen);
  6438. SourceLocation getLocationOfByte(const char *x);
  6439. const Expr *getDataArg(unsigned i) const;
  6440. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6441. const analyze_format_string::ConversionSpecifier &CS,
  6442. const char *startSpecifier, unsigned specifierLen,
  6443. unsigned argIndex);
  6444. template <typename Range>
  6445. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6446. bool IsStringLocation, Range StringRange,
  6447. ArrayRef<FixItHint> Fixit = None);
  6448. };
  6449. } // namespace
  6450. SourceRange CheckFormatHandler::getFormatStringRange() {
  6451. return OrigFormatExpr->getSourceRange();
  6452. }
  6453. CharSourceRange CheckFormatHandler::
  6454. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6455. SourceLocation Start = getLocationOfByte(startSpecifier);
  6456. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6457. // Advance the end SourceLocation by one due to half-open ranges.
  6458. End = End.getLocWithOffset(1);
  6459. return CharSourceRange::getCharRange(Start, End);
  6460. }
  6461. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6462. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6463. S.getLangOpts(), S.Context.getTargetInfo());
  6464. }
  6465. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6466. unsigned specifierLen){
  6467. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6468. getLocationOfByte(startSpecifier),
  6469. /*IsStringLocation*/true,
  6470. getSpecifierRange(startSpecifier, specifierLen));
  6471. }
  6472. void CheckFormatHandler::HandleInvalidLengthModifier(
  6473. const analyze_format_string::FormatSpecifier &FS,
  6474. const analyze_format_string::ConversionSpecifier &CS,
  6475. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6476. using namespace analyze_format_string;
  6477. const LengthModifier &LM = FS.getLengthModifier();
  6478. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6479. // See if we know how to fix this length modifier.
  6480. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6481. if (FixedLM) {
  6482. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6483. getLocationOfByte(LM.getStart()),
  6484. /*IsStringLocation*/true,
  6485. getSpecifierRange(startSpecifier, specifierLen));
  6486. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6487. << FixedLM->toString()
  6488. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6489. } else {
  6490. FixItHint Hint;
  6491. if (DiagID == diag::warn_format_nonsensical_length)
  6492. Hint = FixItHint::CreateRemoval(LMRange);
  6493. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6494. getLocationOfByte(LM.getStart()),
  6495. /*IsStringLocation*/true,
  6496. getSpecifierRange(startSpecifier, specifierLen),
  6497. Hint);
  6498. }
  6499. }
  6500. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6501. const analyze_format_string::FormatSpecifier &FS,
  6502. const char *startSpecifier, unsigned specifierLen) {
  6503. using namespace analyze_format_string;
  6504. const LengthModifier &LM = FS.getLengthModifier();
  6505. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6506. // See if we know how to fix this length modifier.
  6507. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6508. if (FixedLM) {
  6509. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6510. << LM.toString() << 0,
  6511. getLocationOfByte(LM.getStart()),
  6512. /*IsStringLocation*/true,
  6513. getSpecifierRange(startSpecifier, specifierLen));
  6514. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6515. << FixedLM->toString()
  6516. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6517. } else {
  6518. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6519. << LM.toString() << 0,
  6520. getLocationOfByte(LM.getStart()),
  6521. /*IsStringLocation*/true,
  6522. getSpecifierRange(startSpecifier, specifierLen));
  6523. }
  6524. }
  6525. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6526. const analyze_format_string::ConversionSpecifier &CS,
  6527. const char *startSpecifier, unsigned specifierLen) {
  6528. using namespace analyze_format_string;
  6529. // See if we know how to fix this conversion specifier.
  6530. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6531. if (FixedCS) {
  6532. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6533. << CS.toString() << /*conversion specifier*/1,
  6534. getLocationOfByte(CS.getStart()),
  6535. /*IsStringLocation*/true,
  6536. getSpecifierRange(startSpecifier, specifierLen));
  6537. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6538. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6539. << FixedCS->toString()
  6540. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6541. } else {
  6542. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6543. << CS.toString() << /*conversion specifier*/1,
  6544. getLocationOfByte(CS.getStart()),
  6545. /*IsStringLocation*/true,
  6546. getSpecifierRange(startSpecifier, specifierLen));
  6547. }
  6548. }
  6549. void CheckFormatHandler::HandlePosition(const char *startPos,
  6550. unsigned posLen) {
  6551. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6552. getLocationOfByte(startPos),
  6553. /*IsStringLocation*/true,
  6554. getSpecifierRange(startPos, posLen));
  6555. }
  6556. void
  6557. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6558. analyze_format_string::PositionContext p) {
  6559. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6560. << (unsigned) p,
  6561. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6562. getSpecifierRange(startPos, posLen));
  6563. }
  6564. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6565. unsigned posLen) {
  6566. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6567. getLocationOfByte(startPos),
  6568. /*IsStringLocation*/true,
  6569. getSpecifierRange(startPos, posLen));
  6570. }
  6571. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6572. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6573. // The presence of a null character is likely an error.
  6574. EmitFormatDiagnostic(
  6575. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6576. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6577. getFormatStringRange());
  6578. }
  6579. }
  6580. // Note that this may return NULL if there was an error parsing or building
  6581. // one of the argument expressions.
  6582. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6583. return Args[FirstDataArg + i];
  6584. }
  6585. void CheckFormatHandler::DoneProcessing() {
  6586. // Does the number of data arguments exceed the number of
  6587. // format conversions in the format string?
  6588. if (!HasVAListArg) {
  6589. // Find any arguments that weren't covered.
  6590. CoveredArgs.flip();
  6591. signed notCoveredArg = CoveredArgs.find_first();
  6592. if (notCoveredArg >= 0) {
  6593. assert((unsigned)notCoveredArg < NumDataArgs);
  6594. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6595. } else {
  6596. UncoveredArg.setAllCovered();
  6597. }
  6598. }
  6599. }
  6600. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6601. const Expr *ArgExpr) {
  6602. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6603. "Invalid state");
  6604. if (!ArgExpr)
  6605. return;
  6606. SourceLocation Loc = ArgExpr->getBeginLoc();
  6607. if (S.getSourceManager().isInSystemMacro(Loc))
  6608. return;
  6609. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6610. for (auto E : DiagnosticExprs)
  6611. PDiag << E->getSourceRange();
  6612. CheckFormatHandler::EmitFormatDiagnostic(
  6613. S, IsFunctionCall, DiagnosticExprs[0],
  6614. PDiag, Loc, /*IsStringLocation*/false,
  6615. DiagnosticExprs[0]->getSourceRange());
  6616. }
  6617. bool
  6618. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6619. SourceLocation Loc,
  6620. const char *startSpec,
  6621. unsigned specifierLen,
  6622. const char *csStart,
  6623. unsigned csLen) {
  6624. bool keepGoing = true;
  6625. if (argIndex < NumDataArgs) {
  6626. // Consider the argument coverered, even though the specifier doesn't
  6627. // make sense.
  6628. CoveredArgs.set(argIndex);
  6629. }
  6630. else {
  6631. // If argIndex exceeds the number of data arguments we
  6632. // don't issue a warning because that is just a cascade of warnings (and
  6633. // they may have intended '%%' anyway). We don't want to continue processing
  6634. // the format string after this point, however, as we will like just get
  6635. // gibberish when trying to match arguments.
  6636. keepGoing = false;
  6637. }
  6638. StringRef Specifier(csStart, csLen);
  6639. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6640. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6641. // hex value.
  6642. std::string CodePointStr;
  6643. if (!llvm::sys::locale::isPrint(*csStart)) {
  6644. llvm::UTF32 CodePoint;
  6645. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6646. const llvm::UTF8 *E =
  6647. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6648. llvm::ConversionResult Result =
  6649. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6650. if (Result != llvm::conversionOK) {
  6651. unsigned char FirstChar = *csStart;
  6652. CodePoint = (llvm::UTF32)FirstChar;
  6653. }
  6654. llvm::raw_string_ostream OS(CodePointStr);
  6655. if (CodePoint < 256)
  6656. OS << "\\x" << llvm::format("%02x", CodePoint);
  6657. else if (CodePoint <= 0xFFFF)
  6658. OS << "\\u" << llvm::format("%04x", CodePoint);
  6659. else
  6660. OS << "\\U" << llvm::format("%08x", CodePoint);
  6661. OS.flush();
  6662. Specifier = CodePointStr;
  6663. }
  6664. EmitFormatDiagnostic(
  6665. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6666. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6667. return keepGoing;
  6668. }
  6669. void
  6670. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6671. const char *startSpec,
  6672. unsigned specifierLen) {
  6673. EmitFormatDiagnostic(
  6674. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6675. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6676. }
  6677. bool
  6678. CheckFormatHandler::CheckNumArgs(
  6679. const analyze_format_string::FormatSpecifier &FS,
  6680. const analyze_format_string::ConversionSpecifier &CS,
  6681. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6682. if (argIndex >= NumDataArgs) {
  6683. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6684. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6685. << (argIndex+1) << NumDataArgs)
  6686. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6687. EmitFormatDiagnostic(
  6688. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6689. getSpecifierRange(startSpecifier, specifierLen));
  6690. // Since more arguments than conversion tokens are given, by extension
  6691. // all arguments are covered, so mark this as so.
  6692. UncoveredArg.setAllCovered();
  6693. return false;
  6694. }
  6695. return true;
  6696. }
  6697. template<typename Range>
  6698. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6699. SourceLocation Loc,
  6700. bool IsStringLocation,
  6701. Range StringRange,
  6702. ArrayRef<FixItHint> FixIt) {
  6703. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6704. Loc, IsStringLocation, StringRange, FixIt);
  6705. }
  6706. /// If the format string is not within the function call, emit a note
  6707. /// so that the function call and string are in diagnostic messages.
  6708. ///
  6709. /// \param InFunctionCall if true, the format string is within the function
  6710. /// call and only one diagnostic message will be produced. Otherwise, an
  6711. /// extra note will be emitted pointing to location of the format string.
  6712. ///
  6713. /// \param ArgumentExpr the expression that is passed as the format string
  6714. /// argument in the function call. Used for getting locations when two
  6715. /// diagnostics are emitted.
  6716. ///
  6717. /// \param PDiag the callee should already have provided any strings for the
  6718. /// diagnostic message. This function only adds locations and fixits
  6719. /// to diagnostics.
  6720. ///
  6721. /// \param Loc primary location for diagnostic. If two diagnostics are
  6722. /// required, one will be at Loc and a new SourceLocation will be created for
  6723. /// the other one.
  6724. ///
  6725. /// \param IsStringLocation if true, Loc points to the format string should be
  6726. /// used for the note. Otherwise, Loc points to the argument list and will
  6727. /// be used with PDiag.
  6728. ///
  6729. /// \param StringRange some or all of the string to highlight. This is
  6730. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6731. ///
  6732. /// \param FixIt optional fix it hint for the format string.
  6733. template <typename Range>
  6734. void CheckFormatHandler::EmitFormatDiagnostic(
  6735. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6736. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6737. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6738. if (InFunctionCall) {
  6739. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6740. D << StringRange;
  6741. D << FixIt;
  6742. } else {
  6743. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6744. << ArgumentExpr->getSourceRange();
  6745. const Sema::SemaDiagnosticBuilder &Note =
  6746. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6747. diag::note_format_string_defined);
  6748. Note << StringRange;
  6749. Note << FixIt;
  6750. }
  6751. }
  6752. //===--- CHECK: Printf format string checking ------------------------------===//
  6753. namespace {
  6754. class CheckPrintfHandler : public CheckFormatHandler {
  6755. public:
  6756. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6757. const Expr *origFormatExpr,
  6758. const Sema::FormatStringType type, unsigned firstDataArg,
  6759. unsigned numDataArgs, bool isObjC, const char *beg,
  6760. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6761. unsigned formatIdx, bool inFunctionCall,
  6762. Sema::VariadicCallType CallType,
  6763. llvm::SmallBitVector &CheckedVarArgs,
  6764. UncoveredArgHandler &UncoveredArg)
  6765. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6766. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6767. inFunctionCall, CallType, CheckedVarArgs,
  6768. UncoveredArg) {}
  6769. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6770. /// Returns true if '%@' specifiers are allowed in the format string.
  6771. bool allowsObjCArg() const {
  6772. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6773. FSType == Sema::FST_OSTrace;
  6774. }
  6775. bool HandleInvalidPrintfConversionSpecifier(
  6776. const analyze_printf::PrintfSpecifier &FS,
  6777. const char *startSpecifier,
  6778. unsigned specifierLen) override;
  6779. void handleInvalidMaskType(StringRef MaskType) override;
  6780. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6781. const char *startSpecifier,
  6782. unsigned specifierLen) override;
  6783. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6784. const char *StartSpecifier,
  6785. unsigned SpecifierLen,
  6786. const Expr *E);
  6787. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6788. const char *startSpecifier, unsigned specifierLen);
  6789. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6790. const analyze_printf::OptionalAmount &Amt,
  6791. unsigned type,
  6792. const char *startSpecifier, unsigned specifierLen);
  6793. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6794. const analyze_printf::OptionalFlag &flag,
  6795. const char *startSpecifier, unsigned specifierLen);
  6796. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6797. const analyze_printf::OptionalFlag &ignoredFlag,
  6798. const analyze_printf::OptionalFlag &flag,
  6799. const char *startSpecifier, unsigned specifierLen);
  6800. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6801. const Expr *E);
  6802. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6803. unsigned flagLen) override;
  6804. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6805. unsigned flagLen) override;
  6806. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6807. const char *flagsEnd,
  6808. const char *conversionPosition)
  6809. override;
  6810. };
  6811. } // namespace
  6812. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6813. const analyze_printf::PrintfSpecifier &FS,
  6814. const char *startSpecifier,
  6815. unsigned specifierLen) {
  6816. const analyze_printf::PrintfConversionSpecifier &CS =
  6817. FS.getConversionSpecifier();
  6818. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6819. getLocationOfByte(CS.getStart()),
  6820. startSpecifier, specifierLen,
  6821. CS.getStart(), CS.getLength());
  6822. }
  6823. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6824. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6825. }
  6826. bool CheckPrintfHandler::HandleAmount(
  6827. const analyze_format_string::OptionalAmount &Amt,
  6828. unsigned k, const char *startSpecifier,
  6829. unsigned specifierLen) {
  6830. if (Amt.hasDataArgument()) {
  6831. if (!HasVAListArg) {
  6832. unsigned argIndex = Amt.getArgIndex();
  6833. if (argIndex >= NumDataArgs) {
  6834. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6835. << k,
  6836. getLocationOfByte(Amt.getStart()),
  6837. /*IsStringLocation*/true,
  6838. getSpecifierRange(startSpecifier, specifierLen));
  6839. // Don't do any more checking. We will just emit
  6840. // spurious errors.
  6841. return false;
  6842. }
  6843. // Type check the data argument. It should be an 'int'.
  6844. // Although not in conformance with C99, we also allow the argument to be
  6845. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6846. // doesn't emit a warning for that case.
  6847. CoveredArgs.set(argIndex);
  6848. const Expr *Arg = getDataArg(argIndex);
  6849. if (!Arg)
  6850. return false;
  6851. QualType T = Arg->getType();
  6852. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6853. assert(AT.isValid());
  6854. if (!AT.matchesType(S.Context, T)) {
  6855. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6856. << k << AT.getRepresentativeTypeName(S.Context)
  6857. << T << Arg->getSourceRange(),
  6858. getLocationOfByte(Amt.getStart()),
  6859. /*IsStringLocation*/true,
  6860. getSpecifierRange(startSpecifier, specifierLen));
  6861. // Don't do any more checking. We will just emit
  6862. // spurious errors.
  6863. return false;
  6864. }
  6865. }
  6866. }
  6867. return true;
  6868. }
  6869. void CheckPrintfHandler::HandleInvalidAmount(
  6870. const analyze_printf::PrintfSpecifier &FS,
  6871. const analyze_printf::OptionalAmount &Amt,
  6872. unsigned type,
  6873. const char *startSpecifier,
  6874. unsigned specifierLen) {
  6875. const analyze_printf::PrintfConversionSpecifier &CS =
  6876. FS.getConversionSpecifier();
  6877. FixItHint fixit =
  6878. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6879. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6880. Amt.getConstantLength()))
  6881. : FixItHint();
  6882. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6883. << type << CS.toString(),
  6884. getLocationOfByte(Amt.getStart()),
  6885. /*IsStringLocation*/true,
  6886. getSpecifierRange(startSpecifier, specifierLen),
  6887. fixit);
  6888. }
  6889. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6890. const analyze_printf::OptionalFlag &flag,
  6891. const char *startSpecifier,
  6892. unsigned specifierLen) {
  6893. // Warn about pointless flag with a fixit removal.
  6894. const analyze_printf::PrintfConversionSpecifier &CS =
  6895. FS.getConversionSpecifier();
  6896. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6897. << flag.toString() << CS.toString(),
  6898. getLocationOfByte(flag.getPosition()),
  6899. /*IsStringLocation*/true,
  6900. getSpecifierRange(startSpecifier, specifierLen),
  6901. FixItHint::CreateRemoval(
  6902. getSpecifierRange(flag.getPosition(), 1)));
  6903. }
  6904. void CheckPrintfHandler::HandleIgnoredFlag(
  6905. const analyze_printf::PrintfSpecifier &FS,
  6906. const analyze_printf::OptionalFlag &ignoredFlag,
  6907. const analyze_printf::OptionalFlag &flag,
  6908. const char *startSpecifier,
  6909. unsigned specifierLen) {
  6910. // Warn about ignored flag with a fixit removal.
  6911. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6912. << ignoredFlag.toString() << flag.toString(),
  6913. getLocationOfByte(ignoredFlag.getPosition()),
  6914. /*IsStringLocation*/true,
  6915. getSpecifierRange(startSpecifier, specifierLen),
  6916. FixItHint::CreateRemoval(
  6917. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6918. }
  6919. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6920. unsigned flagLen) {
  6921. // Warn about an empty flag.
  6922. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6923. getLocationOfByte(startFlag),
  6924. /*IsStringLocation*/true,
  6925. getSpecifierRange(startFlag, flagLen));
  6926. }
  6927. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6928. unsigned flagLen) {
  6929. // Warn about an invalid flag.
  6930. auto Range = getSpecifierRange(startFlag, flagLen);
  6931. StringRef flag(startFlag, flagLen);
  6932. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6933. getLocationOfByte(startFlag),
  6934. /*IsStringLocation*/true,
  6935. Range, FixItHint::CreateRemoval(Range));
  6936. }
  6937. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6938. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6939. // Warn about using '[...]' without a '@' conversion.
  6940. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6941. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6942. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6943. getLocationOfByte(conversionPosition),
  6944. /*IsStringLocation*/true,
  6945. Range, FixItHint::CreateRemoval(Range));
  6946. }
  6947. // Determines if the specified is a C++ class or struct containing
  6948. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6949. // "c_str()").
  6950. template<typename MemberKind>
  6951. static llvm::SmallPtrSet<MemberKind*, 1>
  6952. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6953. const RecordType *RT = Ty->getAs<RecordType>();
  6954. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6955. if (!RT)
  6956. return Results;
  6957. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6958. if (!RD || !RD->getDefinition())
  6959. return Results;
  6960. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6961. Sema::LookupMemberName);
  6962. R.suppressDiagnostics();
  6963. // We just need to include all members of the right kind turned up by the
  6964. // filter, at this point.
  6965. if (S.LookupQualifiedName(R, RT->getDecl()))
  6966. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6967. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6968. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6969. Results.insert(FK);
  6970. }
  6971. return Results;
  6972. }
  6973. /// Check if we could call '.c_str()' on an object.
  6974. ///
  6975. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6976. /// allow the call, or if it would be ambiguous).
  6977. bool Sema::hasCStrMethod(const Expr *E) {
  6978. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6979. MethodSet Results =
  6980. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6981. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6982. MI != ME; ++MI)
  6983. if ((*MI)->getMinRequiredArguments() == 0)
  6984. return true;
  6985. return false;
  6986. }
  6987. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6988. // better diagnostic if so. AT is assumed to be valid.
  6989. // Returns true when a c_str() conversion method is found.
  6990. bool CheckPrintfHandler::checkForCStrMembers(
  6991. const analyze_printf::ArgType &AT, const Expr *E) {
  6992. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6993. MethodSet Results =
  6994. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6995. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6996. MI != ME; ++MI) {
  6997. const CXXMethodDecl *Method = *MI;
  6998. if (Method->getMinRequiredArguments() == 0 &&
  6999. AT.matchesType(S.Context, Method->getReturnType())) {
  7000. // FIXME: Suggest parens if the expression needs them.
  7001. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  7002. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  7003. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  7004. return true;
  7005. }
  7006. }
  7007. return false;
  7008. }
  7009. bool
  7010. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  7011. &FS,
  7012. const char *startSpecifier,
  7013. unsigned specifierLen) {
  7014. using namespace analyze_format_string;
  7015. using namespace analyze_printf;
  7016. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  7017. if (FS.consumesDataArgument()) {
  7018. if (atFirstArg) {
  7019. atFirstArg = false;
  7020. usesPositionalArgs = FS.usesPositionalArg();
  7021. }
  7022. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7023. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7024. startSpecifier, specifierLen);
  7025. return false;
  7026. }
  7027. }
  7028. // First check if the field width, precision, and conversion specifier
  7029. // have matching data arguments.
  7030. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  7031. startSpecifier, specifierLen)) {
  7032. return false;
  7033. }
  7034. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  7035. startSpecifier, specifierLen)) {
  7036. return false;
  7037. }
  7038. if (!CS.consumesDataArgument()) {
  7039. // FIXME: Technically specifying a precision or field width here
  7040. // makes no sense. Worth issuing a warning at some point.
  7041. return true;
  7042. }
  7043. // Consume the argument.
  7044. unsigned argIndex = FS.getArgIndex();
  7045. if (argIndex < NumDataArgs) {
  7046. // The check to see if the argIndex is valid will come later.
  7047. // We set the bit here because we may exit early from this
  7048. // function if we encounter some other error.
  7049. CoveredArgs.set(argIndex);
  7050. }
  7051. // FreeBSD kernel extensions.
  7052. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  7053. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  7054. // We need at least two arguments.
  7055. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  7056. return false;
  7057. // Claim the second argument.
  7058. CoveredArgs.set(argIndex + 1);
  7059. // Type check the first argument (int for %b, pointer for %D)
  7060. const Expr *Ex = getDataArg(argIndex);
  7061. const analyze_printf::ArgType &AT =
  7062. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  7063. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  7064. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  7065. EmitFormatDiagnostic(
  7066. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7067. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  7068. << false << Ex->getSourceRange(),
  7069. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7070. getSpecifierRange(startSpecifier, specifierLen));
  7071. // Type check the second argument (char * for both %b and %D)
  7072. Ex = getDataArg(argIndex + 1);
  7073. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  7074. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  7075. EmitFormatDiagnostic(
  7076. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7077. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  7078. << false << Ex->getSourceRange(),
  7079. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  7080. getSpecifierRange(startSpecifier, specifierLen));
  7081. return true;
  7082. }
  7083. // Check for using an Objective-C specific conversion specifier
  7084. // in a non-ObjC literal.
  7085. if (!allowsObjCArg() && CS.isObjCArg()) {
  7086. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7087. specifierLen);
  7088. }
  7089. // %P can only be used with os_log.
  7090. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  7091. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7092. specifierLen);
  7093. }
  7094. // %n is not allowed with os_log.
  7095. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  7096. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  7097. getLocationOfByte(CS.getStart()),
  7098. /*IsStringLocation*/ false,
  7099. getSpecifierRange(startSpecifier, specifierLen));
  7100. return true;
  7101. }
  7102. // Only scalars are allowed for os_trace.
  7103. if (FSType == Sema::FST_OSTrace &&
  7104. (CS.getKind() == ConversionSpecifier::PArg ||
  7105. CS.getKind() == ConversionSpecifier::sArg ||
  7106. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  7107. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  7108. specifierLen);
  7109. }
  7110. // Check for use of public/private annotation outside of os_log().
  7111. if (FSType != Sema::FST_OSLog) {
  7112. if (FS.isPublic().isSet()) {
  7113. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7114. << "public",
  7115. getLocationOfByte(FS.isPublic().getPosition()),
  7116. /*IsStringLocation*/ false,
  7117. getSpecifierRange(startSpecifier, specifierLen));
  7118. }
  7119. if (FS.isPrivate().isSet()) {
  7120. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  7121. << "private",
  7122. getLocationOfByte(FS.isPrivate().getPosition()),
  7123. /*IsStringLocation*/ false,
  7124. getSpecifierRange(startSpecifier, specifierLen));
  7125. }
  7126. }
  7127. // Check for invalid use of field width
  7128. if (!FS.hasValidFieldWidth()) {
  7129. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  7130. startSpecifier, specifierLen);
  7131. }
  7132. // Check for invalid use of precision
  7133. if (!FS.hasValidPrecision()) {
  7134. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  7135. startSpecifier, specifierLen);
  7136. }
  7137. // Precision is mandatory for %P specifier.
  7138. if (CS.getKind() == ConversionSpecifier::PArg &&
  7139. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  7140. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  7141. getLocationOfByte(startSpecifier),
  7142. /*IsStringLocation*/ false,
  7143. getSpecifierRange(startSpecifier, specifierLen));
  7144. }
  7145. // Check each flag does not conflict with any other component.
  7146. if (!FS.hasValidThousandsGroupingPrefix())
  7147. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  7148. if (!FS.hasValidLeadingZeros())
  7149. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  7150. if (!FS.hasValidPlusPrefix())
  7151. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  7152. if (!FS.hasValidSpacePrefix())
  7153. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  7154. if (!FS.hasValidAlternativeForm())
  7155. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  7156. if (!FS.hasValidLeftJustified())
  7157. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  7158. // Check that flags are not ignored by another flag
  7159. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  7160. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  7161. startSpecifier, specifierLen);
  7162. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  7163. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  7164. startSpecifier, specifierLen);
  7165. // Check the length modifier is valid with the given conversion specifier.
  7166. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7167. S.getLangOpts()))
  7168. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7169. diag::warn_format_nonsensical_length);
  7170. else if (!FS.hasStandardLengthModifier())
  7171. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7172. else if (!FS.hasStandardLengthConversionCombination())
  7173. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7174. diag::warn_format_non_standard_conversion_spec);
  7175. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7176. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7177. // The remaining checks depend on the data arguments.
  7178. if (HasVAListArg)
  7179. return true;
  7180. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7181. return false;
  7182. const Expr *Arg = getDataArg(argIndex);
  7183. if (!Arg)
  7184. return true;
  7185. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  7186. }
  7187. static bool requiresParensToAddCast(const Expr *E) {
  7188. // FIXME: We should have a general way to reason about operator
  7189. // precedence and whether parens are actually needed here.
  7190. // Take care of a few common cases where they aren't.
  7191. const Expr *Inside = E->IgnoreImpCasts();
  7192. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  7193. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  7194. switch (Inside->getStmtClass()) {
  7195. case Stmt::ArraySubscriptExprClass:
  7196. case Stmt::CallExprClass:
  7197. case Stmt::CharacterLiteralClass:
  7198. case Stmt::CXXBoolLiteralExprClass:
  7199. case Stmt::DeclRefExprClass:
  7200. case Stmt::FloatingLiteralClass:
  7201. case Stmt::IntegerLiteralClass:
  7202. case Stmt::MemberExprClass:
  7203. case Stmt::ObjCArrayLiteralClass:
  7204. case Stmt::ObjCBoolLiteralExprClass:
  7205. case Stmt::ObjCBoxedExprClass:
  7206. case Stmt::ObjCDictionaryLiteralClass:
  7207. case Stmt::ObjCEncodeExprClass:
  7208. case Stmt::ObjCIvarRefExprClass:
  7209. case Stmt::ObjCMessageExprClass:
  7210. case Stmt::ObjCPropertyRefExprClass:
  7211. case Stmt::ObjCStringLiteralClass:
  7212. case Stmt::ObjCSubscriptRefExprClass:
  7213. case Stmt::ParenExprClass:
  7214. case Stmt::StringLiteralClass:
  7215. case Stmt::UnaryOperatorClass:
  7216. return false;
  7217. default:
  7218. return true;
  7219. }
  7220. }
  7221. static std::pair<QualType, StringRef>
  7222. shouldNotPrintDirectly(const ASTContext &Context,
  7223. QualType IntendedTy,
  7224. const Expr *E) {
  7225. // Use a 'while' to peel off layers of typedefs.
  7226. QualType TyTy = IntendedTy;
  7227. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7228. StringRef Name = UserTy->getDecl()->getName();
  7229. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7230. .Case("CFIndex", Context.getNSIntegerType())
  7231. .Case("NSInteger", Context.getNSIntegerType())
  7232. .Case("NSUInteger", Context.getNSUIntegerType())
  7233. .Case("SInt32", Context.IntTy)
  7234. .Case("UInt32", Context.UnsignedIntTy)
  7235. .Default(QualType());
  7236. if (!CastTy.isNull())
  7237. return std::make_pair(CastTy, Name);
  7238. TyTy = UserTy->desugar();
  7239. }
  7240. // Strip parens if necessary.
  7241. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7242. return shouldNotPrintDirectly(Context,
  7243. PE->getSubExpr()->getType(),
  7244. PE->getSubExpr());
  7245. // If this is a conditional expression, then its result type is constructed
  7246. // via usual arithmetic conversions and thus there might be no necessary
  7247. // typedef sugar there. Recurse to operands to check for NSInteger &
  7248. // Co. usage condition.
  7249. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7250. QualType TrueTy, FalseTy;
  7251. StringRef TrueName, FalseName;
  7252. std::tie(TrueTy, TrueName) =
  7253. shouldNotPrintDirectly(Context,
  7254. CO->getTrueExpr()->getType(),
  7255. CO->getTrueExpr());
  7256. std::tie(FalseTy, FalseName) =
  7257. shouldNotPrintDirectly(Context,
  7258. CO->getFalseExpr()->getType(),
  7259. CO->getFalseExpr());
  7260. if (TrueTy == FalseTy)
  7261. return std::make_pair(TrueTy, TrueName);
  7262. else if (TrueTy.isNull())
  7263. return std::make_pair(FalseTy, FalseName);
  7264. else if (FalseTy.isNull())
  7265. return std::make_pair(TrueTy, TrueName);
  7266. }
  7267. return std::make_pair(QualType(), StringRef());
  7268. }
  7269. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7270. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7271. /// type do not count.
  7272. static bool
  7273. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7274. QualType From = ICE->getSubExpr()->getType();
  7275. QualType To = ICE->getType();
  7276. // It's an integer promotion if the destination type is the promoted
  7277. // source type.
  7278. if (ICE->getCastKind() == CK_IntegralCast &&
  7279. From->isPromotableIntegerType() &&
  7280. S.Context.getPromotedIntegerType(From) == To)
  7281. return true;
  7282. // Look through vector types, since we do default argument promotion for
  7283. // those in OpenCL.
  7284. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7285. From = VecTy->getElementType();
  7286. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7287. To = VecTy->getElementType();
  7288. // It's a floating promotion if the source type is a lower rank.
  7289. return ICE->getCastKind() == CK_FloatingCast &&
  7290. S.Context.getFloatingTypeOrder(From, To) < 0;
  7291. }
  7292. bool
  7293. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7294. const char *StartSpecifier,
  7295. unsigned SpecifierLen,
  7296. const Expr *E) {
  7297. using namespace analyze_format_string;
  7298. using namespace analyze_printf;
  7299. // Now type check the data expression that matches the
  7300. // format specifier.
  7301. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7302. if (!AT.isValid())
  7303. return true;
  7304. QualType ExprTy = E->getType();
  7305. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7306. ExprTy = TET->getUnderlyingExpr()->getType();
  7307. }
  7308. const analyze_printf::ArgType::MatchKind Match =
  7309. AT.matchesType(S.Context, ExprTy);
  7310. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7311. if (Match == analyze_printf::ArgType::Match)
  7312. return true;
  7313. // Look through argument promotions for our error message's reported type.
  7314. // This includes the integral and floating promotions, but excludes array
  7315. // and function pointer decay (seeing that an argument intended to be a
  7316. // string has type 'char [6]' is probably more confusing than 'char *') and
  7317. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7318. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7319. if (isArithmeticArgumentPromotion(S, ICE)) {
  7320. E = ICE->getSubExpr();
  7321. ExprTy = E->getType();
  7322. // Check if we didn't match because of an implicit cast from a 'char'
  7323. // or 'short' to an 'int'. This is done because printf is a varargs
  7324. // function.
  7325. if (ICE->getType() == S.Context.IntTy ||
  7326. ICE->getType() == S.Context.UnsignedIntTy) {
  7327. // All further checking is done on the subexpression.
  7328. if (AT.matchesType(S.Context, ExprTy))
  7329. return true;
  7330. }
  7331. }
  7332. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7333. // Special case for 'a', which has type 'int' in C.
  7334. // Note, however, that we do /not/ want to treat multibyte constants like
  7335. // 'MooV' as characters! This form is deprecated but still exists.
  7336. if (ExprTy == S.Context.IntTy)
  7337. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7338. ExprTy = S.Context.CharTy;
  7339. }
  7340. // Look through enums to their underlying type.
  7341. bool IsEnum = false;
  7342. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7343. ExprTy = EnumTy->getDecl()->getIntegerType();
  7344. IsEnum = true;
  7345. }
  7346. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7347. // If the argument is an integer of some kind, believe the %C and suggest
  7348. // a cast instead of changing the conversion specifier.
  7349. QualType IntendedTy = ExprTy;
  7350. if (isObjCContext() &&
  7351. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7352. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7353. !ExprTy->isCharType()) {
  7354. // 'unichar' is defined as a typedef of unsigned short, but we should
  7355. // prefer using the typedef if it is visible.
  7356. IntendedTy = S.Context.UnsignedShortTy;
  7357. // While we are here, check if the value is an IntegerLiteral that happens
  7358. // to be within the valid range.
  7359. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7360. const llvm::APInt &V = IL->getValue();
  7361. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7362. return true;
  7363. }
  7364. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7365. Sema::LookupOrdinaryName);
  7366. if (S.LookupName(Result, S.getCurScope())) {
  7367. NamedDecl *ND = Result.getFoundDecl();
  7368. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7369. if (TD->getUnderlyingType() == IntendedTy)
  7370. IntendedTy = S.Context.getTypedefType(TD);
  7371. }
  7372. }
  7373. }
  7374. // Special-case some of Darwin's platform-independence types by suggesting
  7375. // casts to primitive types that are known to be large enough.
  7376. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7377. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7378. QualType CastTy;
  7379. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7380. if (!CastTy.isNull()) {
  7381. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7382. // (long in ASTContext). Only complain to pedants.
  7383. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7384. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7385. AT.matchesType(S.Context, CastTy))
  7386. Pedantic = true;
  7387. IntendedTy = CastTy;
  7388. ShouldNotPrintDirectly = true;
  7389. }
  7390. }
  7391. // We may be able to offer a FixItHint if it is a supported type.
  7392. PrintfSpecifier fixedFS = FS;
  7393. bool Success =
  7394. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7395. if (Success) {
  7396. // Get the fix string from the fixed format specifier
  7397. SmallString<16> buf;
  7398. llvm::raw_svector_ostream os(buf);
  7399. fixedFS.toString(os);
  7400. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7401. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7402. unsigned Diag =
  7403. Pedantic
  7404. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7405. : diag::warn_format_conversion_argument_type_mismatch;
  7406. // In this case, the specifier is wrong and should be changed to match
  7407. // the argument.
  7408. EmitFormatDiagnostic(S.PDiag(Diag)
  7409. << AT.getRepresentativeTypeName(S.Context)
  7410. << IntendedTy << IsEnum << E->getSourceRange(),
  7411. E->getBeginLoc(),
  7412. /*IsStringLocation*/ false, SpecRange,
  7413. FixItHint::CreateReplacement(SpecRange, os.str()));
  7414. } else {
  7415. // The canonical type for formatting this value is different from the
  7416. // actual type of the expression. (This occurs, for example, with Darwin's
  7417. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7418. // should be printed as 'long' for 64-bit compatibility.)
  7419. // Rather than emitting a normal format/argument mismatch, we want to
  7420. // add a cast to the recommended type (and correct the format string
  7421. // if necessary).
  7422. SmallString<16> CastBuf;
  7423. llvm::raw_svector_ostream CastFix(CastBuf);
  7424. CastFix << "(";
  7425. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7426. CastFix << ")";
  7427. SmallVector<FixItHint,4> Hints;
  7428. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7429. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7430. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7431. // If there's already a cast present, just replace it.
  7432. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7433. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7434. } else if (!requiresParensToAddCast(E)) {
  7435. // If the expression has high enough precedence,
  7436. // just write the C-style cast.
  7437. Hints.push_back(
  7438. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7439. } else {
  7440. // Otherwise, add parens around the expression as well as the cast.
  7441. CastFix << "(";
  7442. Hints.push_back(
  7443. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7444. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7445. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7446. }
  7447. if (ShouldNotPrintDirectly) {
  7448. // The expression has a type that should not be printed directly.
  7449. // We extract the name from the typedef because we don't want to show
  7450. // the underlying type in the diagnostic.
  7451. StringRef Name;
  7452. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7453. Name = TypedefTy->getDecl()->getName();
  7454. else
  7455. Name = CastTyName;
  7456. unsigned Diag = Pedantic
  7457. ? diag::warn_format_argument_needs_cast_pedantic
  7458. : diag::warn_format_argument_needs_cast;
  7459. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7460. << E->getSourceRange(),
  7461. E->getBeginLoc(), /*IsStringLocation=*/false,
  7462. SpecRange, Hints);
  7463. } else {
  7464. // In this case, the expression could be printed using a different
  7465. // specifier, but we've decided that the specifier is probably correct
  7466. // and we should cast instead. Just use the normal warning message.
  7467. EmitFormatDiagnostic(
  7468. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7469. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7470. << E->getSourceRange(),
  7471. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7472. }
  7473. }
  7474. } else {
  7475. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7476. SpecifierLen);
  7477. // Since the warning for passing non-POD types to variadic functions
  7478. // was deferred until now, we emit a warning for non-POD
  7479. // arguments here.
  7480. switch (S.isValidVarArgType(ExprTy)) {
  7481. case Sema::VAK_Valid:
  7482. case Sema::VAK_ValidInCXX11: {
  7483. unsigned Diag =
  7484. Pedantic
  7485. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7486. : diag::warn_format_conversion_argument_type_mismatch;
  7487. EmitFormatDiagnostic(
  7488. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7489. << IsEnum << CSR << E->getSourceRange(),
  7490. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7491. break;
  7492. }
  7493. case Sema::VAK_Undefined:
  7494. case Sema::VAK_MSVCUndefined:
  7495. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7496. << S.getLangOpts().CPlusPlus11 << ExprTy
  7497. << CallType
  7498. << AT.getRepresentativeTypeName(S.Context) << CSR
  7499. << E->getSourceRange(),
  7500. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7501. checkForCStrMembers(AT, E);
  7502. break;
  7503. case Sema::VAK_Invalid:
  7504. if (ExprTy->isObjCObjectType())
  7505. EmitFormatDiagnostic(
  7506. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7507. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7508. << AT.getRepresentativeTypeName(S.Context) << CSR
  7509. << E->getSourceRange(),
  7510. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7511. else
  7512. // FIXME: If this is an initializer list, suggest removing the braces
  7513. // or inserting a cast to the target type.
  7514. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7515. << isa<InitListExpr>(E) << ExprTy << CallType
  7516. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7517. break;
  7518. }
  7519. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7520. "format string specifier index out of range");
  7521. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7522. }
  7523. return true;
  7524. }
  7525. //===--- CHECK: Scanf format string checking ------------------------------===//
  7526. namespace {
  7527. class CheckScanfHandler : public CheckFormatHandler {
  7528. public:
  7529. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7530. const Expr *origFormatExpr, Sema::FormatStringType type,
  7531. unsigned firstDataArg, unsigned numDataArgs,
  7532. const char *beg, bool hasVAListArg,
  7533. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7534. bool inFunctionCall, Sema::VariadicCallType CallType,
  7535. llvm::SmallBitVector &CheckedVarArgs,
  7536. UncoveredArgHandler &UncoveredArg)
  7537. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7538. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7539. inFunctionCall, CallType, CheckedVarArgs,
  7540. UncoveredArg) {}
  7541. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7542. const char *startSpecifier,
  7543. unsigned specifierLen) override;
  7544. bool HandleInvalidScanfConversionSpecifier(
  7545. const analyze_scanf::ScanfSpecifier &FS,
  7546. const char *startSpecifier,
  7547. unsigned specifierLen) override;
  7548. void HandleIncompleteScanList(const char *start, const char *end) override;
  7549. };
  7550. } // namespace
  7551. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7552. const char *end) {
  7553. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7554. getLocationOfByte(end), /*IsStringLocation*/true,
  7555. getSpecifierRange(start, end - start));
  7556. }
  7557. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7558. const analyze_scanf::ScanfSpecifier &FS,
  7559. const char *startSpecifier,
  7560. unsigned specifierLen) {
  7561. const analyze_scanf::ScanfConversionSpecifier &CS =
  7562. FS.getConversionSpecifier();
  7563. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7564. getLocationOfByte(CS.getStart()),
  7565. startSpecifier, specifierLen,
  7566. CS.getStart(), CS.getLength());
  7567. }
  7568. bool CheckScanfHandler::HandleScanfSpecifier(
  7569. const analyze_scanf::ScanfSpecifier &FS,
  7570. const char *startSpecifier,
  7571. unsigned specifierLen) {
  7572. using namespace analyze_scanf;
  7573. using namespace analyze_format_string;
  7574. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7575. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7576. // be used to decide if we are using positional arguments consistently.
  7577. if (FS.consumesDataArgument()) {
  7578. if (atFirstArg) {
  7579. atFirstArg = false;
  7580. usesPositionalArgs = FS.usesPositionalArg();
  7581. }
  7582. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7583. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7584. startSpecifier, specifierLen);
  7585. return false;
  7586. }
  7587. }
  7588. // Check if the field with is non-zero.
  7589. const OptionalAmount &Amt = FS.getFieldWidth();
  7590. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7591. if (Amt.getConstantAmount() == 0) {
  7592. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7593. Amt.getConstantLength());
  7594. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7595. getLocationOfByte(Amt.getStart()),
  7596. /*IsStringLocation*/true, R,
  7597. FixItHint::CreateRemoval(R));
  7598. }
  7599. }
  7600. if (!FS.consumesDataArgument()) {
  7601. // FIXME: Technically specifying a precision or field width here
  7602. // makes no sense. Worth issuing a warning at some point.
  7603. return true;
  7604. }
  7605. // Consume the argument.
  7606. unsigned argIndex = FS.getArgIndex();
  7607. if (argIndex < NumDataArgs) {
  7608. // The check to see if the argIndex is valid will come later.
  7609. // We set the bit here because we may exit early from this
  7610. // function if we encounter some other error.
  7611. CoveredArgs.set(argIndex);
  7612. }
  7613. // Check the length modifier is valid with the given conversion specifier.
  7614. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7615. S.getLangOpts()))
  7616. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7617. diag::warn_format_nonsensical_length);
  7618. else if (!FS.hasStandardLengthModifier())
  7619. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7620. else if (!FS.hasStandardLengthConversionCombination())
  7621. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7622. diag::warn_format_non_standard_conversion_spec);
  7623. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7624. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7625. // The remaining checks depend on the data arguments.
  7626. if (HasVAListArg)
  7627. return true;
  7628. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7629. return false;
  7630. // Check that the argument type matches the format specifier.
  7631. const Expr *Ex = getDataArg(argIndex);
  7632. if (!Ex)
  7633. return true;
  7634. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7635. if (!AT.isValid()) {
  7636. return true;
  7637. }
  7638. analyze_format_string::ArgType::MatchKind Match =
  7639. AT.matchesType(S.Context, Ex->getType());
  7640. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7641. if (Match == analyze_format_string::ArgType::Match)
  7642. return true;
  7643. ScanfSpecifier fixedFS = FS;
  7644. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7645. S.getLangOpts(), S.Context);
  7646. unsigned Diag =
  7647. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7648. : diag::warn_format_conversion_argument_type_mismatch;
  7649. if (Success) {
  7650. // Get the fix string from the fixed format specifier.
  7651. SmallString<128> buf;
  7652. llvm::raw_svector_ostream os(buf);
  7653. fixedFS.toString(os);
  7654. EmitFormatDiagnostic(
  7655. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7656. << Ex->getType() << false << Ex->getSourceRange(),
  7657. Ex->getBeginLoc(),
  7658. /*IsStringLocation*/ false,
  7659. getSpecifierRange(startSpecifier, specifierLen),
  7660. FixItHint::CreateReplacement(
  7661. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7662. } else {
  7663. EmitFormatDiagnostic(S.PDiag(Diag)
  7664. << AT.getRepresentativeTypeName(S.Context)
  7665. << Ex->getType() << false << Ex->getSourceRange(),
  7666. Ex->getBeginLoc(),
  7667. /*IsStringLocation*/ false,
  7668. getSpecifierRange(startSpecifier, specifierLen));
  7669. }
  7670. return true;
  7671. }
  7672. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7673. const Expr *OrigFormatExpr,
  7674. ArrayRef<const Expr *> Args,
  7675. bool HasVAListArg, unsigned format_idx,
  7676. unsigned firstDataArg,
  7677. Sema::FormatStringType Type,
  7678. bool inFunctionCall,
  7679. Sema::VariadicCallType CallType,
  7680. llvm::SmallBitVector &CheckedVarArgs,
  7681. UncoveredArgHandler &UncoveredArg) {
  7682. // CHECK: is the format string a wide literal?
  7683. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7684. CheckFormatHandler::EmitFormatDiagnostic(
  7685. S, inFunctionCall, Args[format_idx],
  7686. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7687. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7688. return;
  7689. }
  7690. // Str - The format string. NOTE: this is NOT null-terminated!
  7691. StringRef StrRef = FExpr->getString();
  7692. const char *Str = StrRef.data();
  7693. // Account for cases where the string literal is truncated in a declaration.
  7694. const ConstantArrayType *T =
  7695. S.Context.getAsConstantArrayType(FExpr->getType());
  7696. assert(T && "String literal not of constant array type!");
  7697. size_t TypeSize = T->getSize().getZExtValue();
  7698. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7699. const unsigned numDataArgs = Args.size() - firstDataArg;
  7700. // Emit a warning if the string literal is truncated and does not contain an
  7701. // embedded null character.
  7702. if (TypeSize <= StrRef.size() &&
  7703. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7704. CheckFormatHandler::EmitFormatDiagnostic(
  7705. S, inFunctionCall, Args[format_idx],
  7706. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7707. FExpr->getBeginLoc(),
  7708. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7709. return;
  7710. }
  7711. // CHECK: empty format string?
  7712. if (StrLen == 0 && numDataArgs > 0) {
  7713. CheckFormatHandler::EmitFormatDiagnostic(
  7714. S, inFunctionCall, Args[format_idx],
  7715. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7716. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7717. return;
  7718. }
  7719. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7720. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7721. Type == Sema::FST_OSTrace) {
  7722. CheckPrintfHandler H(
  7723. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7724. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7725. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7726. CheckedVarArgs, UncoveredArg);
  7727. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7728. S.getLangOpts(),
  7729. S.Context.getTargetInfo(),
  7730. Type == Sema::FST_FreeBSDKPrintf))
  7731. H.DoneProcessing();
  7732. } else if (Type == Sema::FST_Scanf) {
  7733. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7734. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7735. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7736. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7737. S.getLangOpts(),
  7738. S.Context.getTargetInfo()))
  7739. H.DoneProcessing();
  7740. } // TODO: handle other formats
  7741. }
  7742. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7743. // Str - The format string. NOTE: this is NOT null-terminated!
  7744. StringRef StrRef = FExpr->getString();
  7745. const char *Str = StrRef.data();
  7746. // Account for cases where the string literal is truncated in a declaration.
  7747. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7748. assert(T && "String literal not of constant array type!");
  7749. size_t TypeSize = T->getSize().getZExtValue();
  7750. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7751. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7752. getLangOpts(),
  7753. Context.getTargetInfo());
  7754. }
  7755. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7756. // Returns the related absolute value function that is larger, of 0 if one
  7757. // does not exist.
  7758. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7759. switch (AbsFunction) {
  7760. default:
  7761. return 0;
  7762. case Builtin::BI__builtin_abs:
  7763. return Builtin::BI__builtin_labs;
  7764. case Builtin::BI__builtin_labs:
  7765. return Builtin::BI__builtin_llabs;
  7766. case Builtin::BI__builtin_llabs:
  7767. return 0;
  7768. case Builtin::BI__builtin_fabsf:
  7769. return Builtin::BI__builtin_fabs;
  7770. case Builtin::BI__builtin_fabs:
  7771. return Builtin::BI__builtin_fabsl;
  7772. case Builtin::BI__builtin_fabsl:
  7773. return 0;
  7774. case Builtin::BI__builtin_cabsf:
  7775. return Builtin::BI__builtin_cabs;
  7776. case Builtin::BI__builtin_cabs:
  7777. return Builtin::BI__builtin_cabsl;
  7778. case Builtin::BI__builtin_cabsl:
  7779. return 0;
  7780. case Builtin::BIabs:
  7781. return Builtin::BIlabs;
  7782. case Builtin::BIlabs:
  7783. return Builtin::BIllabs;
  7784. case Builtin::BIllabs:
  7785. return 0;
  7786. case Builtin::BIfabsf:
  7787. return Builtin::BIfabs;
  7788. case Builtin::BIfabs:
  7789. return Builtin::BIfabsl;
  7790. case Builtin::BIfabsl:
  7791. return 0;
  7792. case Builtin::BIcabsf:
  7793. return Builtin::BIcabs;
  7794. case Builtin::BIcabs:
  7795. return Builtin::BIcabsl;
  7796. case Builtin::BIcabsl:
  7797. return 0;
  7798. }
  7799. }
  7800. // Returns the argument type of the absolute value function.
  7801. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7802. unsigned AbsType) {
  7803. if (AbsType == 0)
  7804. return QualType();
  7805. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7806. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7807. if (Error != ASTContext::GE_None)
  7808. return QualType();
  7809. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7810. if (!FT)
  7811. return QualType();
  7812. if (FT->getNumParams() != 1)
  7813. return QualType();
  7814. return FT->getParamType(0);
  7815. }
  7816. // Returns the best absolute value function, or zero, based on type and
  7817. // current absolute value function.
  7818. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7819. unsigned AbsFunctionKind) {
  7820. unsigned BestKind = 0;
  7821. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7822. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7823. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7824. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7825. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7826. if (BestKind == 0)
  7827. BestKind = Kind;
  7828. else if (Context.hasSameType(ParamType, ArgType)) {
  7829. BestKind = Kind;
  7830. break;
  7831. }
  7832. }
  7833. }
  7834. return BestKind;
  7835. }
  7836. enum AbsoluteValueKind {
  7837. AVK_Integer,
  7838. AVK_Floating,
  7839. AVK_Complex
  7840. };
  7841. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7842. if (T->isIntegralOrEnumerationType())
  7843. return AVK_Integer;
  7844. if (T->isRealFloatingType())
  7845. return AVK_Floating;
  7846. if (T->isAnyComplexType())
  7847. return AVK_Complex;
  7848. llvm_unreachable("Type not integer, floating, or complex");
  7849. }
  7850. // Changes the absolute value function to a different type. Preserves whether
  7851. // the function is a builtin.
  7852. static unsigned changeAbsFunction(unsigned AbsKind,
  7853. AbsoluteValueKind ValueKind) {
  7854. switch (ValueKind) {
  7855. case AVK_Integer:
  7856. switch (AbsKind) {
  7857. default:
  7858. return 0;
  7859. case Builtin::BI__builtin_fabsf:
  7860. case Builtin::BI__builtin_fabs:
  7861. case Builtin::BI__builtin_fabsl:
  7862. case Builtin::BI__builtin_cabsf:
  7863. case Builtin::BI__builtin_cabs:
  7864. case Builtin::BI__builtin_cabsl:
  7865. return Builtin::BI__builtin_abs;
  7866. case Builtin::BIfabsf:
  7867. case Builtin::BIfabs:
  7868. case Builtin::BIfabsl:
  7869. case Builtin::BIcabsf:
  7870. case Builtin::BIcabs:
  7871. case Builtin::BIcabsl:
  7872. return Builtin::BIabs;
  7873. }
  7874. case AVK_Floating:
  7875. switch (AbsKind) {
  7876. default:
  7877. return 0;
  7878. case Builtin::BI__builtin_abs:
  7879. case Builtin::BI__builtin_labs:
  7880. case Builtin::BI__builtin_llabs:
  7881. case Builtin::BI__builtin_cabsf:
  7882. case Builtin::BI__builtin_cabs:
  7883. case Builtin::BI__builtin_cabsl:
  7884. return Builtin::BI__builtin_fabsf;
  7885. case Builtin::BIabs:
  7886. case Builtin::BIlabs:
  7887. case Builtin::BIllabs:
  7888. case Builtin::BIcabsf:
  7889. case Builtin::BIcabs:
  7890. case Builtin::BIcabsl:
  7891. return Builtin::BIfabsf;
  7892. }
  7893. case AVK_Complex:
  7894. switch (AbsKind) {
  7895. default:
  7896. return 0;
  7897. case Builtin::BI__builtin_abs:
  7898. case Builtin::BI__builtin_labs:
  7899. case Builtin::BI__builtin_llabs:
  7900. case Builtin::BI__builtin_fabsf:
  7901. case Builtin::BI__builtin_fabs:
  7902. case Builtin::BI__builtin_fabsl:
  7903. return Builtin::BI__builtin_cabsf;
  7904. case Builtin::BIabs:
  7905. case Builtin::BIlabs:
  7906. case Builtin::BIllabs:
  7907. case Builtin::BIfabsf:
  7908. case Builtin::BIfabs:
  7909. case Builtin::BIfabsl:
  7910. return Builtin::BIcabsf;
  7911. }
  7912. }
  7913. llvm_unreachable("Unable to convert function");
  7914. }
  7915. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7916. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7917. if (!FnInfo)
  7918. return 0;
  7919. switch (FDecl->getBuiltinID()) {
  7920. default:
  7921. return 0;
  7922. case Builtin::BI__builtin_abs:
  7923. case Builtin::BI__builtin_fabs:
  7924. case Builtin::BI__builtin_fabsf:
  7925. case Builtin::BI__builtin_fabsl:
  7926. case Builtin::BI__builtin_labs:
  7927. case Builtin::BI__builtin_llabs:
  7928. case Builtin::BI__builtin_cabs:
  7929. case Builtin::BI__builtin_cabsf:
  7930. case Builtin::BI__builtin_cabsl:
  7931. case Builtin::BIabs:
  7932. case Builtin::BIlabs:
  7933. case Builtin::BIllabs:
  7934. case Builtin::BIfabs:
  7935. case Builtin::BIfabsf:
  7936. case Builtin::BIfabsl:
  7937. case Builtin::BIcabs:
  7938. case Builtin::BIcabsf:
  7939. case Builtin::BIcabsl:
  7940. return FDecl->getBuiltinID();
  7941. }
  7942. llvm_unreachable("Unknown Builtin type");
  7943. }
  7944. // If the replacement is valid, emit a note with replacement function.
  7945. // Additionally, suggest including the proper header if not already included.
  7946. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7947. unsigned AbsKind, QualType ArgType) {
  7948. bool EmitHeaderHint = true;
  7949. const char *HeaderName = nullptr;
  7950. const char *FunctionName = nullptr;
  7951. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7952. FunctionName = "std::abs";
  7953. if (ArgType->isIntegralOrEnumerationType()) {
  7954. HeaderName = "cstdlib";
  7955. } else if (ArgType->isRealFloatingType()) {
  7956. HeaderName = "cmath";
  7957. } else {
  7958. llvm_unreachable("Invalid Type");
  7959. }
  7960. // Lookup all std::abs
  7961. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7962. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7963. R.suppressDiagnostics();
  7964. S.LookupQualifiedName(R, Std);
  7965. for (const auto *I : R) {
  7966. const FunctionDecl *FDecl = nullptr;
  7967. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7968. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7969. } else {
  7970. FDecl = dyn_cast<FunctionDecl>(I);
  7971. }
  7972. if (!FDecl)
  7973. continue;
  7974. // Found std::abs(), check that they are the right ones.
  7975. if (FDecl->getNumParams() != 1)
  7976. continue;
  7977. // Check that the parameter type can handle the argument.
  7978. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7979. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7980. S.Context.getTypeSize(ArgType) <=
  7981. S.Context.getTypeSize(ParamType)) {
  7982. // Found a function, don't need the header hint.
  7983. EmitHeaderHint = false;
  7984. break;
  7985. }
  7986. }
  7987. }
  7988. } else {
  7989. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7990. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7991. if (HeaderName) {
  7992. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7993. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7994. R.suppressDiagnostics();
  7995. S.LookupName(R, S.getCurScope());
  7996. if (R.isSingleResult()) {
  7997. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7998. if (FD && FD->getBuiltinID() == AbsKind) {
  7999. EmitHeaderHint = false;
  8000. } else {
  8001. return;
  8002. }
  8003. } else if (!R.empty()) {
  8004. return;
  8005. }
  8006. }
  8007. }
  8008. S.Diag(Loc, diag::note_replace_abs_function)
  8009. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  8010. if (!HeaderName)
  8011. return;
  8012. if (!EmitHeaderHint)
  8013. return;
  8014. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  8015. << FunctionName;
  8016. }
  8017. template <std::size_t StrLen>
  8018. static bool IsStdFunction(const FunctionDecl *FDecl,
  8019. const char (&Str)[StrLen]) {
  8020. if (!FDecl)
  8021. return false;
  8022. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  8023. return false;
  8024. if (!FDecl->isInStdNamespace())
  8025. return false;
  8026. return true;
  8027. }
  8028. // Warn when using the wrong abs() function.
  8029. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  8030. const FunctionDecl *FDecl) {
  8031. if (Call->getNumArgs() != 1)
  8032. return;
  8033. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  8034. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  8035. if (AbsKind == 0 && !IsStdAbs)
  8036. return;
  8037. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8038. QualType ParamType = Call->getArg(0)->getType();
  8039. // Unsigned types cannot be negative. Suggest removing the absolute value
  8040. // function call.
  8041. if (ArgType->isUnsignedIntegerType()) {
  8042. const char *FunctionName =
  8043. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  8044. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  8045. Diag(Call->getExprLoc(), diag::note_remove_abs)
  8046. << FunctionName
  8047. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  8048. return;
  8049. }
  8050. // Taking the absolute value of a pointer is very suspicious, they probably
  8051. // wanted to index into an array, dereference a pointer, call a function, etc.
  8052. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  8053. unsigned DiagType = 0;
  8054. if (ArgType->isFunctionType())
  8055. DiagType = 1;
  8056. else if (ArgType->isArrayType())
  8057. DiagType = 2;
  8058. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  8059. return;
  8060. }
  8061. // std::abs has overloads which prevent most of the absolute value problems
  8062. // from occurring.
  8063. if (IsStdAbs)
  8064. return;
  8065. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  8066. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  8067. // The argument and parameter are the same kind. Check if they are the right
  8068. // size.
  8069. if (ArgValueKind == ParamValueKind) {
  8070. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  8071. return;
  8072. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  8073. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  8074. << FDecl << ArgType << ParamType;
  8075. if (NewAbsKind == 0)
  8076. return;
  8077. emitReplacement(*this, Call->getExprLoc(),
  8078. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8079. return;
  8080. }
  8081. // ArgValueKind != ParamValueKind
  8082. // The wrong type of absolute value function was used. Attempt to find the
  8083. // proper one.
  8084. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  8085. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  8086. if (NewAbsKind == 0)
  8087. return;
  8088. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  8089. << FDecl << ParamValueKind << ArgValueKind;
  8090. emitReplacement(*this, Call->getExprLoc(),
  8091. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  8092. }
  8093. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  8094. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  8095. const FunctionDecl *FDecl) {
  8096. if (!Call || !FDecl) return;
  8097. // Ignore template specializations and macros.
  8098. if (inTemplateInstantiation()) return;
  8099. if (Call->getExprLoc().isMacroID()) return;
  8100. // Only care about the one template argument, two function parameter std::max
  8101. if (Call->getNumArgs() != 2) return;
  8102. if (!IsStdFunction(FDecl, "max")) return;
  8103. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  8104. if (!ArgList) return;
  8105. if (ArgList->size() != 1) return;
  8106. // Check that template type argument is unsigned integer.
  8107. const auto& TA = ArgList->get(0);
  8108. if (TA.getKind() != TemplateArgument::Type) return;
  8109. QualType ArgType = TA.getAsType();
  8110. if (!ArgType->isUnsignedIntegerType()) return;
  8111. // See if either argument is a literal zero.
  8112. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  8113. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  8114. if (!MTE) return false;
  8115. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  8116. if (!Num) return false;
  8117. if (Num->getValue() != 0) return false;
  8118. return true;
  8119. };
  8120. const Expr *FirstArg = Call->getArg(0);
  8121. const Expr *SecondArg = Call->getArg(1);
  8122. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  8123. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  8124. // Only warn when exactly one argument is zero.
  8125. if (IsFirstArgZero == IsSecondArgZero) return;
  8126. SourceRange FirstRange = FirstArg->getSourceRange();
  8127. SourceRange SecondRange = SecondArg->getSourceRange();
  8128. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  8129. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  8130. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  8131. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  8132. SourceRange RemovalRange;
  8133. if (IsFirstArgZero) {
  8134. RemovalRange = SourceRange(FirstRange.getBegin(),
  8135. SecondRange.getBegin().getLocWithOffset(-1));
  8136. } else {
  8137. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  8138. SecondRange.getEnd());
  8139. }
  8140. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  8141. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  8142. << FixItHint::CreateRemoval(RemovalRange);
  8143. }
  8144. //===--- CHECK: Standard memory functions ---------------------------------===//
  8145. /// Takes the expression passed to the size_t parameter of functions
  8146. /// such as memcmp, strncat, etc and warns if it's a comparison.
  8147. ///
  8148. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  8149. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  8150. IdentifierInfo *FnName,
  8151. SourceLocation FnLoc,
  8152. SourceLocation RParenLoc) {
  8153. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  8154. if (!Size)
  8155. return false;
  8156. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  8157. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  8158. return false;
  8159. SourceRange SizeRange = Size->getSourceRange();
  8160. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  8161. << SizeRange << FnName;
  8162. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  8163. << FnName
  8164. << FixItHint::CreateInsertion(
  8165. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  8166. << FixItHint::CreateRemoval(RParenLoc);
  8167. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  8168. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  8169. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  8170. ")");
  8171. return true;
  8172. }
  8173. /// Determine whether the given type is or contains a dynamic class type
  8174. /// (e.g., whether it has a vtable).
  8175. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  8176. bool &IsContained) {
  8177. // Look through array types while ignoring qualifiers.
  8178. const Type *Ty = T->getBaseElementTypeUnsafe();
  8179. IsContained = false;
  8180. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  8181. RD = RD ? RD->getDefinition() : nullptr;
  8182. if (!RD || RD->isInvalidDecl())
  8183. return nullptr;
  8184. if (RD->isDynamicClass())
  8185. return RD;
  8186. // Check all the fields. If any bases were dynamic, the class is dynamic.
  8187. // It's impossible for a class to transitively contain itself by value, so
  8188. // infinite recursion is impossible.
  8189. for (auto *FD : RD->fields()) {
  8190. bool SubContained;
  8191. if (const CXXRecordDecl *ContainedRD =
  8192. getContainedDynamicClass(FD->getType(), SubContained)) {
  8193. IsContained = true;
  8194. return ContainedRD;
  8195. }
  8196. }
  8197. return nullptr;
  8198. }
  8199. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  8200. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  8201. if (Unary->getKind() == UETT_SizeOf)
  8202. return Unary;
  8203. return nullptr;
  8204. }
  8205. /// If E is a sizeof expression, returns its argument expression,
  8206. /// otherwise returns NULL.
  8207. static const Expr *getSizeOfExprArg(const Expr *E) {
  8208. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8209. if (!SizeOf->isArgumentType())
  8210. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  8211. return nullptr;
  8212. }
  8213. /// If E is a sizeof expression, returns its argument type.
  8214. static QualType getSizeOfArgType(const Expr *E) {
  8215. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  8216. return SizeOf->getTypeOfArgument();
  8217. return QualType();
  8218. }
  8219. namespace {
  8220. struct SearchNonTrivialToInitializeField
  8221. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  8222. using Super =
  8223. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  8224. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  8225. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8226. SourceLocation SL) {
  8227. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8228. asDerived().visitArray(PDIK, AT, SL);
  8229. return;
  8230. }
  8231. Super::visitWithKind(PDIK, FT, SL);
  8232. }
  8233. void visitARCStrong(QualType FT, SourceLocation SL) {
  8234. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8235. }
  8236. void visitARCWeak(QualType FT, SourceLocation SL) {
  8237. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8238. }
  8239. void visitStruct(QualType FT, SourceLocation SL) {
  8240. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8241. visit(FD->getType(), FD->getLocation());
  8242. }
  8243. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8244. const ArrayType *AT, SourceLocation SL) {
  8245. visit(getContext().getBaseElementType(AT), SL);
  8246. }
  8247. void visitTrivial(QualType FT, SourceLocation SL) {}
  8248. static void diag(QualType RT, const Expr *E, Sema &S) {
  8249. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8250. }
  8251. ASTContext &getContext() { return S.getASTContext(); }
  8252. const Expr *E;
  8253. Sema &S;
  8254. };
  8255. struct SearchNonTrivialToCopyField
  8256. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8257. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8258. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8259. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8260. SourceLocation SL) {
  8261. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8262. asDerived().visitArray(PCK, AT, SL);
  8263. return;
  8264. }
  8265. Super::visitWithKind(PCK, FT, SL);
  8266. }
  8267. void visitARCStrong(QualType FT, SourceLocation SL) {
  8268. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8269. }
  8270. void visitARCWeak(QualType FT, SourceLocation SL) {
  8271. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8272. }
  8273. void visitStruct(QualType FT, SourceLocation SL) {
  8274. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8275. visit(FD->getType(), FD->getLocation());
  8276. }
  8277. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8278. SourceLocation SL) {
  8279. visit(getContext().getBaseElementType(AT), SL);
  8280. }
  8281. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8282. SourceLocation SL) {}
  8283. void visitTrivial(QualType FT, SourceLocation SL) {}
  8284. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8285. static void diag(QualType RT, const Expr *E, Sema &S) {
  8286. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8287. }
  8288. ASTContext &getContext() { return S.getASTContext(); }
  8289. const Expr *E;
  8290. Sema &S;
  8291. };
  8292. }
  8293. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8294. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8295. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8296. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8297. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8298. return false;
  8299. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8300. doesExprLikelyComputeSize(BO->getRHS());
  8301. }
  8302. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8303. }
  8304. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8305. ///
  8306. /// \code
  8307. /// #define MACRO 0
  8308. /// foo(MACRO);
  8309. /// foo(0);
  8310. /// \endcode
  8311. ///
  8312. /// This should return true for the first call to foo, but not for the second
  8313. /// (regardless of whether foo is a macro or function).
  8314. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8315. SourceLocation CallLoc,
  8316. SourceLocation ArgLoc) {
  8317. if (!CallLoc.isMacroID())
  8318. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8319. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8320. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8321. }
  8322. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8323. /// last two arguments transposed.
  8324. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8325. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8326. return;
  8327. const Expr *SizeArg =
  8328. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8329. auto isLiteralZero = [](const Expr *E) {
  8330. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8331. };
  8332. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8333. SourceLocation CallLoc = Call->getRParenLoc();
  8334. SourceManager &SM = S.getSourceManager();
  8335. if (isLiteralZero(SizeArg) &&
  8336. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8337. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8338. // Some platforms #define bzero to __builtin_memset. See if this is the
  8339. // case, and if so, emit a better diagnostic.
  8340. if (BId == Builtin::BIbzero ||
  8341. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8342. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8343. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8344. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8345. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8346. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8347. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8348. }
  8349. return;
  8350. }
  8351. // If the second argument to a memset is a sizeof expression and the third
  8352. // isn't, this is also likely an error. This should catch
  8353. // 'memset(buf, sizeof(buf), 0xff)'.
  8354. if (BId == Builtin::BImemset &&
  8355. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8356. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8357. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8358. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8359. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8360. return;
  8361. }
  8362. }
  8363. /// Check for dangerous or invalid arguments to memset().
  8364. ///
  8365. /// This issues warnings on known problematic, dangerous or unspecified
  8366. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8367. /// function calls.
  8368. ///
  8369. /// \param Call The call expression to diagnose.
  8370. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8371. unsigned BId,
  8372. IdentifierInfo *FnName) {
  8373. assert(BId != 0);
  8374. // It is possible to have a non-standard definition of memset. Validate
  8375. // we have enough arguments, and if not, abort further checking.
  8376. unsigned ExpectedNumArgs =
  8377. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8378. if (Call->getNumArgs() < ExpectedNumArgs)
  8379. return;
  8380. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8381. BId == Builtin::BIstrndup ? 1 : 2);
  8382. unsigned LenArg =
  8383. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8384. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8385. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8386. Call->getBeginLoc(), Call->getRParenLoc()))
  8387. return;
  8388. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8389. CheckMemaccessSize(*this, BId, Call);
  8390. // We have special checking when the length is a sizeof expression.
  8391. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8392. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8393. llvm::FoldingSetNodeID SizeOfArgID;
  8394. // Although widely used, 'bzero' is not a standard function. Be more strict
  8395. // with the argument types before allowing diagnostics and only allow the
  8396. // form bzero(ptr, sizeof(...)).
  8397. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8398. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8399. return;
  8400. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8401. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8402. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8403. QualType DestTy = Dest->getType();
  8404. QualType PointeeTy;
  8405. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8406. PointeeTy = DestPtrTy->getPointeeType();
  8407. // Never warn about void type pointers. This can be used to suppress
  8408. // false positives.
  8409. if (PointeeTy->isVoidType())
  8410. continue;
  8411. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8412. // actually comparing the expressions for equality. Because computing the
  8413. // expression IDs can be expensive, we only do this if the diagnostic is
  8414. // enabled.
  8415. if (SizeOfArg &&
  8416. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8417. SizeOfArg->getExprLoc())) {
  8418. // We only compute IDs for expressions if the warning is enabled, and
  8419. // cache the sizeof arg's ID.
  8420. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8421. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8422. llvm::FoldingSetNodeID DestID;
  8423. Dest->Profile(DestID, Context, true);
  8424. if (DestID == SizeOfArgID) {
  8425. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8426. // over sizeof(src) as well.
  8427. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8428. StringRef ReadableName = FnName->getName();
  8429. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8430. if (UnaryOp->getOpcode() == UO_AddrOf)
  8431. ActionIdx = 1; // If its an address-of operator, just remove it.
  8432. if (!PointeeTy->isIncompleteType() &&
  8433. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8434. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8435. // suggest an explicit length.
  8436. // If the function is defined as a builtin macro, do not show macro
  8437. // expansion.
  8438. SourceLocation SL = SizeOfArg->getExprLoc();
  8439. SourceRange DSR = Dest->getSourceRange();
  8440. SourceRange SSR = SizeOfArg->getSourceRange();
  8441. SourceManager &SM = getSourceManager();
  8442. if (SM.isMacroArgExpansion(SL)) {
  8443. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8444. SL = SM.getSpellingLoc(SL);
  8445. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8446. SM.getSpellingLoc(DSR.getEnd()));
  8447. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8448. SM.getSpellingLoc(SSR.getEnd()));
  8449. }
  8450. DiagRuntimeBehavior(SL, SizeOfArg,
  8451. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8452. << ReadableName
  8453. << PointeeTy
  8454. << DestTy
  8455. << DSR
  8456. << SSR);
  8457. DiagRuntimeBehavior(SL, SizeOfArg,
  8458. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8459. << ActionIdx
  8460. << SSR);
  8461. break;
  8462. }
  8463. }
  8464. // Also check for cases where the sizeof argument is the exact same
  8465. // type as the memory argument, and where it points to a user-defined
  8466. // record type.
  8467. if (SizeOfArgTy != QualType()) {
  8468. if (PointeeTy->isRecordType() &&
  8469. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8470. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8471. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8472. << FnName << SizeOfArgTy << ArgIdx
  8473. << PointeeTy << Dest->getSourceRange()
  8474. << LenExpr->getSourceRange());
  8475. break;
  8476. }
  8477. }
  8478. } else if (DestTy->isArrayType()) {
  8479. PointeeTy = DestTy;
  8480. }
  8481. if (PointeeTy == QualType())
  8482. continue;
  8483. // Always complain about dynamic classes.
  8484. bool IsContained;
  8485. if (const CXXRecordDecl *ContainedRD =
  8486. getContainedDynamicClass(PointeeTy, IsContained)) {
  8487. unsigned OperationType = 0;
  8488. const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
  8489. // "overwritten" if we're warning about the destination for any call
  8490. // but memcmp; otherwise a verb appropriate to the call.
  8491. if (ArgIdx != 0 || IsCmp) {
  8492. if (BId == Builtin::BImemcpy)
  8493. OperationType = 1;
  8494. else if(BId == Builtin::BImemmove)
  8495. OperationType = 2;
  8496. else if (IsCmp)
  8497. OperationType = 3;
  8498. }
  8499. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8500. PDiag(diag::warn_dyn_class_memaccess)
  8501. << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
  8502. << IsContained << ContainedRD << OperationType
  8503. << Call->getCallee()->getSourceRange());
  8504. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8505. BId != Builtin::BImemset)
  8506. DiagRuntimeBehavior(
  8507. Dest->getExprLoc(), Dest,
  8508. PDiag(diag::warn_arc_object_memaccess)
  8509. << ArgIdx << FnName << PointeeTy
  8510. << Call->getCallee()->getSourceRange());
  8511. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8512. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8513. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8514. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8515. PDiag(diag::warn_cstruct_memaccess)
  8516. << ArgIdx << FnName << PointeeTy << 0);
  8517. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8518. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8519. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8520. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8521. PDiag(diag::warn_cstruct_memaccess)
  8522. << ArgIdx << FnName << PointeeTy << 1);
  8523. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8524. } else {
  8525. continue;
  8526. }
  8527. } else
  8528. continue;
  8529. DiagRuntimeBehavior(
  8530. Dest->getExprLoc(), Dest,
  8531. PDiag(diag::note_bad_memaccess_silence)
  8532. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8533. break;
  8534. }
  8535. }
  8536. // A little helper routine: ignore addition and subtraction of integer literals.
  8537. // This intentionally does not ignore all integer constant expressions because
  8538. // we don't want to remove sizeof().
  8539. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8540. Ex = Ex->IgnoreParenCasts();
  8541. while (true) {
  8542. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8543. if (!BO || !BO->isAdditiveOp())
  8544. break;
  8545. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8546. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8547. if (isa<IntegerLiteral>(RHS))
  8548. Ex = LHS;
  8549. else if (isa<IntegerLiteral>(LHS))
  8550. Ex = RHS;
  8551. else
  8552. break;
  8553. }
  8554. return Ex;
  8555. }
  8556. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8557. ASTContext &Context) {
  8558. // Only handle constant-sized or VLAs, but not flexible members.
  8559. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8560. // Only issue the FIXIT for arrays of size > 1.
  8561. if (CAT->getSize().getSExtValue() <= 1)
  8562. return false;
  8563. } else if (!Ty->isVariableArrayType()) {
  8564. return false;
  8565. }
  8566. return true;
  8567. }
  8568. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8569. // be the size of the source, instead of the destination.
  8570. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8571. IdentifierInfo *FnName) {
  8572. // Don't crash if the user has the wrong number of arguments
  8573. unsigned NumArgs = Call->getNumArgs();
  8574. if ((NumArgs != 3) && (NumArgs != 4))
  8575. return;
  8576. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8577. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8578. const Expr *CompareWithSrc = nullptr;
  8579. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8580. Call->getBeginLoc(), Call->getRParenLoc()))
  8581. return;
  8582. // Look for 'strlcpy(dst, x, sizeof(x))'
  8583. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8584. CompareWithSrc = Ex;
  8585. else {
  8586. // Look for 'strlcpy(dst, x, strlen(x))'
  8587. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8588. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8589. SizeCall->getNumArgs() == 1)
  8590. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8591. }
  8592. }
  8593. if (!CompareWithSrc)
  8594. return;
  8595. // Determine if the argument to sizeof/strlen is equal to the source
  8596. // argument. In principle there's all kinds of things you could do
  8597. // here, for instance creating an == expression and evaluating it with
  8598. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8599. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8600. if (!SrcArgDRE)
  8601. return;
  8602. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8603. if (!CompareWithSrcDRE ||
  8604. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8605. return;
  8606. const Expr *OriginalSizeArg = Call->getArg(2);
  8607. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8608. << OriginalSizeArg->getSourceRange() << FnName;
  8609. // Output a FIXIT hint if the destination is an array (rather than a
  8610. // pointer to an array). This could be enhanced to handle some
  8611. // pointers if we know the actual size, like if DstArg is 'array+2'
  8612. // we could say 'sizeof(array)-2'.
  8613. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8614. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8615. return;
  8616. SmallString<128> sizeString;
  8617. llvm::raw_svector_ostream OS(sizeString);
  8618. OS << "sizeof(";
  8619. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8620. OS << ")";
  8621. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8622. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8623. OS.str());
  8624. }
  8625. /// Check if two expressions refer to the same declaration.
  8626. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8627. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8628. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8629. return D1->getDecl() == D2->getDecl();
  8630. return false;
  8631. }
  8632. static const Expr *getStrlenExprArg(const Expr *E) {
  8633. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8634. const FunctionDecl *FD = CE->getDirectCallee();
  8635. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8636. return nullptr;
  8637. return CE->getArg(0)->IgnoreParenCasts();
  8638. }
  8639. return nullptr;
  8640. }
  8641. // Warn on anti-patterns as the 'size' argument to strncat.
  8642. // The correct size argument should look like following:
  8643. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8644. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8645. IdentifierInfo *FnName) {
  8646. // Don't crash if the user has the wrong number of arguments.
  8647. if (CE->getNumArgs() < 3)
  8648. return;
  8649. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8650. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8651. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8652. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8653. CE->getRParenLoc()))
  8654. return;
  8655. // Identify common expressions, which are wrongly used as the size argument
  8656. // to strncat and may lead to buffer overflows.
  8657. unsigned PatternType = 0;
  8658. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8659. // - sizeof(dst)
  8660. if (referToTheSameDecl(SizeOfArg, DstArg))
  8661. PatternType = 1;
  8662. // - sizeof(src)
  8663. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8664. PatternType = 2;
  8665. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8666. if (BE->getOpcode() == BO_Sub) {
  8667. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8668. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8669. // - sizeof(dst) - strlen(dst)
  8670. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8671. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8672. PatternType = 1;
  8673. // - sizeof(src) - (anything)
  8674. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8675. PatternType = 2;
  8676. }
  8677. }
  8678. if (PatternType == 0)
  8679. return;
  8680. // Generate the diagnostic.
  8681. SourceLocation SL = LenArg->getBeginLoc();
  8682. SourceRange SR = LenArg->getSourceRange();
  8683. SourceManager &SM = getSourceManager();
  8684. // If the function is defined as a builtin macro, do not show macro expansion.
  8685. if (SM.isMacroArgExpansion(SL)) {
  8686. SL = SM.getSpellingLoc(SL);
  8687. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8688. SM.getSpellingLoc(SR.getEnd()));
  8689. }
  8690. // Check if the destination is an array (rather than a pointer to an array).
  8691. QualType DstTy = DstArg->getType();
  8692. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8693. Context);
  8694. if (!isKnownSizeArray) {
  8695. if (PatternType == 1)
  8696. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8697. else
  8698. Diag(SL, diag::warn_strncat_src_size) << SR;
  8699. return;
  8700. }
  8701. if (PatternType == 1)
  8702. Diag(SL, diag::warn_strncat_large_size) << SR;
  8703. else
  8704. Diag(SL, diag::warn_strncat_src_size) << SR;
  8705. SmallString<128> sizeString;
  8706. llvm::raw_svector_ostream OS(sizeString);
  8707. OS << "sizeof(";
  8708. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8709. OS << ") - ";
  8710. OS << "strlen(";
  8711. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8712. OS << ") - 1";
  8713. Diag(SL, diag::note_strncat_wrong_size)
  8714. << FixItHint::CreateReplacement(SR, OS.str());
  8715. }
  8716. void
  8717. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8718. SourceLocation ReturnLoc,
  8719. bool isObjCMethod,
  8720. const AttrVec *Attrs,
  8721. const FunctionDecl *FD) {
  8722. // Check if the return value is null but should not be.
  8723. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8724. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8725. CheckNonNullExpr(*this, RetValExp))
  8726. Diag(ReturnLoc, diag::warn_null_ret)
  8727. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8728. // C++11 [basic.stc.dynamic.allocation]p4:
  8729. // If an allocation function declared with a non-throwing
  8730. // exception-specification fails to allocate storage, it shall return
  8731. // a null pointer. Any other allocation function that fails to allocate
  8732. // storage shall indicate failure only by throwing an exception [...]
  8733. if (FD) {
  8734. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8735. if (Op == OO_New || Op == OO_Array_New) {
  8736. const FunctionProtoType *Proto
  8737. = FD->getType()->castAs<FunctionProtoType>();
  8738. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8739. CheckNonNullExpr(*this, RetValExp))
  8740. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8741. << FD << getLangOpts().CPlusPlus11;
  8742. }
  8743. }
  8744. }
  8745. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8746. /// Check for comparisons of floating point operands using != and ==.
  8747. /// Issue a warning if these are no self-comparisons, as they are not likely
  8748. /// to do what the programmer intended.
  8749. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8750. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8751. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8752. // Special case: check for x == x (which is OK).
  8753. // Do not emit warnings for such cases.
  8754. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8755. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8756. if (DRL->getDecl() == DRR->getDecl())
  8757. return;
  8758. // Special case: check for comparisons against literals that can be exactly
  8759. // represented by APFloat. In such cases, do not emit a warning. This
  8760. // is a heuristic: often comparison against such literals are used to
  8761. // detect if a value in a variable has not changed. This clearly can
  8762. // lead to false negatives.
  8763. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8764. if (FLL->isExact())
  8765. return;
  8766. } else
  8767. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8768. if (FLR->isExact())
  8769. return;
  8770. // Check for comparisons with builtin types.
  8771. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8772. if (CL->getBuiltinCallee())
  8773. return;
  8774. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8775. if (CR->getBuiltinCallee())
  8776. return;
  8777. // Emit the diagnostic.
  8778. Diag(Loc, diag::warn_floatingpoint_eq)
  8779. << LHS->getSourceRange() << RHS->getSourceRange();
  8780. }
  8781. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8782. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8783. namespace {
  8784. /// Structure recording the 'active' range of an integer-valued
  8785. /// expression.
  8786. struct IntRange {
  8787. /// The number of bits active in the int.
  8788. unsigned Width;
  8789. /// True if the int is known not to have negative values.
  8790. bool NonNegative;
  8791. IntRange(unsigned Width, bool NonNegative)
  8792. : Width(Width), NonNegative(NonNegative) {}
  8793. /// Returns the range of the bool type.
  8794. static IntRange forBoolType() {
  8795. return IntRange(1, true);
  8796. }
  8797. /// Returns the range of an opaque value of the given integral type.
  8798. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8799. return forValueOfCanonicalType(C,
  8800. T->getCanonicalTypeInternal().getTypePtr());
  8801. }
  8802. /// Returns the range of an opaque value of a canonical integral type.
  8803. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8804. assert(T->isCanonicalUnqualified());
  8805. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8806. T = VT->getElementType().getTypePtr();
  8807. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8808. T = CT->getElementType().getTypePtr();
  8809. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8810. T = AT->getValueType().getTypePtr();
  8811. if (!C.getLangOpts().CPlusPlus) {
  8812. // For enum types in C code, use the underlying datatype.
  8813. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8814. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8815. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8816. // For enum types in C++, use the known bit width of the enumerators.
  8817. EnumDecl *Enum = ET->getDecl();
  8818. // In C++11, enums can have a fixed underlying type. Use this type to
  8819. // compute the range.
  8820. if (Enum->isFixed()) {
  8821. return IntRange(C.getIntWidth(QualType(T, 0)),
  8822. !ET->isSignedIntegerOrEnumerationType());
  8823. }
  8824. unsigned NumPositive = Enum->getNumPositiveBits();
  8825. unsigned NumNegative = Enum->getNumNegativeBits();
  8826. if (NumNegative == 0)
  8827. return IntRange(NumPositive, true/*NonNegative*/);
  8828. else
  8829. return IntRange(std::max(NumPositive + 1, NumNegative),
  8830. false/*NonNegative*/);
  8831. }
  8832. const BuiltinType *BT = cast<BuiltinType>(T);
  8833. assert(BT->isInteger());
  8834. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8835. }
  8836. /// Returns the "target" range of a canonical integral type, i.e.
  8837. /// the range of values expressible in the type.
  8838. ///
  8839. /// This matches forValueOfCanonicalType except that enums have the
  8840. /// full range of their type, not the range of their enumerators.
  8841. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8842. assert(T->isCanonicalUnqualified());
  8843. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8844. T = VT->getElementType().getTypePtr();
  8845. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8846. T = CT->getElementType().getTypePtr();
  8847. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8848. T = AT->getValueType().getTypePtr();
  8849. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8850. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8851. const BuiltinType *BT = cast<BuiltinType>(T);
  8852. assert(BT->isInteger());
  8853. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8854. }
  8855. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8856. static IntRange join(IntRange L, IntRange R) {
  8857. return IntRange(std::max(L.Width, R.Width),
  8858. L.NonNegative && R.NonNegative);
  8859. }
  8860. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8861. static IntRange meet(IntRange L, IntRange R) {
  8862. return IntRange(std::min(L.Width, R.Width),
  8863. L.NonNegative || R.NonNegative);
  8864. }
  8865. };
  8866. } // namespace
  8867. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8868. unsigned MaxWidth) {
  8869. if (value.isSigned() && value.isNegative())
  8870. return IntRange(value.getMinSignedBits(), false);
  8871. if (value.getBitWidth() > MaxWidth)
  8872. value = value.trunc(MaxWidth);
  8873. // isNonNegative() just checks the sign bit without considering
  8874. // signedness.
  8875. return IntRange(value.getActiveBits(), true);
  8876. }
  8877. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8878. unsigned MaxWidth) {
  8879. if (result.isInt())
  8880. return GetValueRange(C, result.getInt(), MaxWidth);
  8881. if (result.isVector()) {
  8882. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8883. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8884. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8885. R = IntRange::join(R, El);
  8886. }
  8887. return R;
  8888. }
  8889. if (result.isComplexInt()) {
  8890. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8891. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8892. return IntRange::join(R, I);
  8893. }
  8894. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8895. // Assume it might use arbitrary bits.
  8896. // FIXME: The only reason we need to pass the type in here is to get
  8897. // the sign right on this one case. It would be nice if APValue
  8898. // preserved this.
  8899. assert(result.isLValue() || result.isAddrLabelDiff());
  8900. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8901. }
  8902. static QualType GetExprType(const Expr *E) {
  8903. QualType Ty = E->getType();
  8904. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8905. Ty = AtomicRHS->getValueType();
  8906. return Ty;
  8907. }
  8908. /// Pseudo-evaluate the given integer expression, estimating the
  8909. /// range of values it might take.
  8910. ///
  8911. /// \param MaxWidth - the width to which the value will be truncated
  8912. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
  8913. bool InConstantContext) {
  8914. E = E->IgnoreParens();
  8915. // Try a full evaluation first.
  8916. Expr::EvalResult result;
  8917. if (E->EvaluateAsRValue(result, C, InConstantContext))
  8918. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8919. // I think we only want to look through implicit casts here; if the
  8920. // user has an explicit widening cast, we should treat the value as
  8921. // being of the new, wider type.
  8922. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8923. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8924. return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
  8925. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8926. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8927. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8928. // Assume that non-integer casts can span the full range of the type.
  8929. if (!isIntegerCast)
  8930. return OutputTypeRange;
  8931. IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
  8932. std::min(MaxWidth, OutputTypeRange.Width),
  8933. InConstantContext);
  8934. // Bail out if the subexpr's range is as wide as the cast type.
  8935. if (SubRange.Width >= OutputTypeRange.Width)
  8936. return OutputTypeRange;
  8937. // Otherwise, we take the smaller width, and we're non-negative if
  8938. // either the output type or the subexpr is.
  8939. return IntRange(SubRange.Width,
  8940. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8941. }
  8942. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8943. // If we can fold the condition, just take that operand.
  8944. bool CondResult;
  8945. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8946. return GetExprRange(C,
  8947. CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
  8948. MaxWidth, InConstantContext);
  8949. // Otherwise, conservatively merge.
  8950. IntRange L =
  8951. GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
  8952. IntRange R =
  8953. GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
  8954. return IntRange::join(L, R);
  8955. }
  8956. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8957. switch (BO->getOpcode()) {
  8958. case BO_Cmp:
  8959. llvm_unreachable("builtin <=> should have class type");
  8960. // Boolean-valued operations are single-bit and positive.
  8961. case BO_LAnd:
  8962. case BO_LOr:
  8963. case BO_LT:
  8964. case BO_GT:
  8965. case BO_LE:
  8966. case BO_GE:
  8967. case BO_EQ:
  8968. case BO_NE:
  8969. return IntRange::forBoolType();
  8970. // The type of the assignments is the type of the LHS, so the RHS
  8971. // is not necessarily the same type.
  8972. case BO_MulAssign:
  8973. case BO_DivAssign:
  8974. case BO_RemAssign:
  8975. case BO_AddAssign:
  8976. case BO_SubAssign:
  8977. case BO_XorAssign:
  8978. case BO_OrAssign:
  8979. // TODO: bitfields?
  8980. return IntRange::forValueOfType(C, GetExprType(E));
  8981. // Simple assignments just pass through the RHS, which will have
  8982. // been coerced to the LHS type.
  8983. case BO_Assign:
  8984. // TODO: bitfields?
  8985. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  8986. // Operations with opaque sources are black-listed.
  8987. case BO_PtrMemD:
  8988. case BO_PtrMemI:
  8989. return IntRange::forValueOfType(C, GetExprType(E));
  8990. // Bitwise-and uses the *infinum* of the two source ranges.
  8991. case BO_And:
  8992. case BO_AndAssign:
  8993. return IntRange::meet(
  8994. GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
  8995. GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
  8996. // Left shift gets black-listed based on a judgement call.
  8997. case BO_Shl:
  8998. // ...except that we want to treat '1 << (blah)' as logically
  8999. // positive. It's an important idiom.
  9000. if (IntegerLiteral *I
  9001. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  9002. if (I->getValue() == 1) {
  9003. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  9004. return IntRange(R.Width, /*NonNegative*/ true);
  9005. }
  9006. }
  9007. LLVM_FALLTHROUGH;
  9008. case BO_ShlAssign:
  9009. return IntRange::forValueOfType(C, GetExprType(E));
  9010. // Right shift by a constant can narrow its left argument.
  9011. case BO_Shr:
  9012. case BO_ShrAssign: {
  9013. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9014. // If the shift amount is a positive constant, drop the width by
  9015. // that much.
  9016. llvm::APSInt shift;
  9017. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  9018. shift.isNonNegative()) {
  9019. unsigned zext = shift.getZExtValue();
  9020. if (zext >= L.Width)
  9021. L.Width = (L.NonNegative ? 0 : 1);
  9022. else
  9023. L.Width -= zext;
  9024. }
  9025. return L;
  9026. }
  9027. // Comma acts as its right operand.
  9028. case BO_Comma:
  9029. return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9030. // Black-list pointer subtractions.
  9031. case BO_Sub:
  9032. if (BO->getLHS()->getType()->isPointerType())
  9033. return IntRange::forValueOfType(C, GetExprType(E));
  9034. break;
  9035. // The width of a division result is mostly determined by the size
  9036. // of the LHS.
  9037. case BO_Div: {
  9038. // Don't 'pre-truncate' the operands.
  9039. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9040. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9041. // If the divisor is constant, use that.
  9042. llvm::APSInt divisor;
  9043. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  9044. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  9045. if (log2 >= L.Width)
  9046. L.Width = (L.NonNegative ? 0 : 1);
  9047. else
  9048. L.Width = std::min(L.Width - log2, MaxWidth);
  9049. return L;
  9050. }
  9051. // Otherwise, just use the LHS's width.
  9052. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9053. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  9054. }
  9055. // The result of a remainder can't be larger than the result of
  9056. // either side.
  9057. case BO_Rem: {
  9058. // Don't 'pre-truncate' the operands.
  9059. unsigned opWidth = C.getIntWidth(GetExprType(E));
  9060. IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
  9061. IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
  9062. IntRange meet = IntRange::meet(L, R);
  9063. meet.Width = std::min(meet.Width, MaxWidth);
  9064. return meet;
  9065. }
  9066. // The default behavior is okay for these.
  9067. case BO_Mul:
  9068. case BO_Add:
  9069. case BO_Xor:
  9070. case BO_Or:
  9071. break;
  9072. }
  9073. // The default case is to treat the operation as if it were closed
  9074. // on the narrowest type that encompasses both operands.
  9075. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
  9076. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
  9077. return IntRange::join(L, R);
  9078. }
  9079. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  9080. switch (UO->getOpcode()) {
  9081. // Boolean-valued operations are white-listed.
  9082. case UO_LNot:
  9083. return IntRange::forBoolType();
  9084. // Operations with opaque sources are black-listed.
  9085. case UO_Deref:
  9086. case UO_AddrOf: // should be impossible
  9087. return IntRange::forValueOfType(C, GetExprType(E));
  9088. default:
  9089. return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
  9090. }
  9091. }
  9092. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  9093. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
  9094. if (const auto *BitField = E->getSourceBitField())
  9095. return IntRange(BitField->getBitWidthValue(C),
  9096. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  9097. return IntRange::forValueOfType(C, GetExprType(E));
  9098. }
  9099. static IntRange GetExprRange(ASTContext &C, const Expr *E,
  9100. bool InConstantContext) {
  9101. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
  9102. }
  9103. /// Checks whether the given value, which currently has the given
  9104. /// source semantics, has the same value when coerced through the
  9105. /// target semantics.
  9106. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  9107. const llvm::fltSemantics &Src,
  9108. const llvm::fltSemantics &Tgt) {
  9109. llvm::APFloat truncated = value;
  9110. bool ignored;
  9111. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9112. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  9113. return truncated.bitwiseIsEqual(value);
  9114. }
  9115. /// Checks whether the given value, which currently has the given
  9116. /// source semantics, has the same value when coerced through the
  9117. /// target semantics.
  9118. ///
  9119. /// The value might be a vector of floats (or a complex number).
  9120. static bool IsSameFloatAfterCast(const APValue &value,
  9121. const llvm::fltSemantics &Src,
  9122. const llvm::fltSemantics &Tgt) {
  9123. if (value.isFloat())
  9124. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  9125. if (value.isVector()) {
  9126. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  9127. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  9128. return false;
  9129. return true;
  9130. }
  9131. assert(value.isComplexFloat());
  9132. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  9133. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  9134. }
  9135. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  9136. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  9137. // Suppress cases where we are comparing against an enum constant.
  9138. if (const DeclRefExpr *DR =
  9139. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  9140. if (isa<EnumConstantDecl>(DR->getDecl()))
  9141. return true;
  9142. // Suppress cases where the value is expanded from a macro, unless that macro
  9143. // is how a language represents a boolean literal. This is the case in both C
  9144. // and Objective-C.
  9145. SourceLocation BeginLoc = E->getBeginLoc();
  9146. if (BeginLoc.isMacroID()) {
  9147. StringRef MacroName = Lexer::getImmediateMacroName(
  9148. BeginLoc, S.getSourceManager(), S.getLangOpts());
  9149. return MacroName != "YES" && MacroName != "NO" &&
  9150. MacroName != "true" && MacroName != "false";
  9151. }
  9152. return false;
  9153. }
  9154. static bool isKnownToHaveUnsignedValue(Expr *E) {
  9155. return E->getType()->isIntegerType() &&
  9156. (!E->getType()->isSignedIntegerType() ||
  9157. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  9158. }
  9159. namespace {
  9160. /// The promoted range of values of a type. In general this has the
  9161. /// following structure:
  9162. ///
  9163. /// |-----------| . . . |-----------|
  9164. /// ^ ^ ^ ^
  9165. /// Min HoleMin HoleMax Max
  9166. ///
  9167. /// ... where there is only a hole if a signed type is promoted to unsigned
  9168. /// (in which case Min and Max are the smallest and largest representable
  9169. /// values).
  9170. struct PromotedRange {
  9171. // Min, or HoleMax if there is a hole.
  9172. llvm::APSInt PromotedMin;
  9173. // Max, or HoleMin if there is a hole.
  9174. llvm::APSInt PromotedMax;
  9175. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  9176. if (R.Width == 0)
  9177. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  9178. else if (R.Width >= BitWidth && !Unsigned) {
  9179. // Promotion made the type *narrower*. This happens when promoting
  9180. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  9181. // Treat all values of 'signed int' as being in range for now.
  9182. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  9183. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  9184. } else {
  9185. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  9186. .extOrTrunc(BitWidth);
  9187. PromotedMin.setIsUnsigned(Unsigned);
  9188. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  9189. .extOrTrunc(BitWidth);
  9190. PromotedMax.setIsUnsigned(Unsigned);
  9191. }
  9192. }
  9193. // Determine whether this range is contiguous (has no hole).
  9194. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  9195. // Where a constant value is within the range.
  9196. enum ComparisonResult {
  9197. LT = 0x1,
  9198. LE = 0x2,
  9199. GT = 0x4,
  9200. GE = 0x8,
  9201. EQ = 0x10,
  9202. NE = 0x20,
  9203. InRangeFlag = 0x40,
  9204. Less = LE | LT | NE,
  9205. Min = LE | InRangeFlag,
  9206. InRange = InRangeFlag,
  9207. Max = GE | InRangeFlag,
  9208. Greater = GE | GT | NE,
  9209. OnlyValue = LE | GE | EQ | InRangeFlag,
  9210. InHole = NE
  9211. };
  9212. ComparisonResult compare(const llvm::APSInt &Value) const {
  9213. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  9214. Value.isUnsigned() == PromotedMin.isUnsigned());
  9215. if (!isContiguous()) {
  9216. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  9217. if (Value.isMinValue()) return Min;
  9218. if (Value.isMaxValue()) return Max;
  9219. if (Value >= PromotedMin) return InRange;
  9220. if (Value <= PromotedMax) return InRange;
  9221. return InHole;
  9222. }
  9223. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  9224. case -1: return Less;
  9225. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  9226. case 1:
  9227. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  9228. case -1: return InRange;
  9229. case 0: return Max;
  9230. case 1: return Greater;
  9231. }
  9232. }
  9233. llvm_unreachable("impossible compare result");
  9234. }
  9235. static llvm::Optional<StringRef>
  9236. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  9237. if (Op == BO_Cmp) {
  9238. ComparisonResult LTFlag = LT, GTFlag = GT;
  9239. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9240. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9241. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9242. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9243. return llvm::None;
  9244. }
  9245. ComparisonResult TrueFlag, FalseFlag;
  9246. if (Op == BO_EQ) {
  9247. TrueFlag = EQ;
  9248. FalseFlag = NE;
  9249. } else if (Op == BO_NE) {
  9250. TrueFlag = NE;
  9251. FalseFlag = EQ;
  9252. } else {
  9253. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9254. TrueFlag = LT;
  9255. FalseFlag = GE;
  9256. } else {
  9257. TrueFlag = GT;
  9258. FalseFlag = LE;
  9259. }
  9260. if (Op == BO_GE || Op == BO_LE)
  9261. std::swap(TrueFlag, FalseFlag);
  9262. }
  9263. if (R & TrueFlag)
  9264. return StringRef("true");
  9265. if (R & FalseFlag)
  9266. return StringRef("false");
  9267. return llvm::None;
  9268. }
  9269. };
  9270. }
  9271. static bool HasEnumType(Expr *E) {
  9272. // Strip off implicit integral promotions.
  9273. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9274. if (ICE->getCastKind() != CK_IntegralCast &&
  9275. ICE->getCastKind() != CK_NoOp)
  9276. break;
  9277. E = ICE->getSubExpr();
  9278. }
  9279. return E->getType()->isEnumeralType();
  9280. }
  9281. static int classifyConstantValue(Expr *Constant) {
  9282. // The values of this enumeration are used in the diagnostics
  9283. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9284. enum ConstantValueKind {
  9285. Miscellaneous = 0,
  9286. LiteralTrue,
  9287. LiteralFalse
  9288. };
  9289. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9290. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9291. : ConstantValueKind::LiteralFalse;
  9292. return ConstantValueKind::Miscellaneous;
  9293. }
  9294. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9295. Expr *Constant, Expr *Other,
  9296. const llvm::APSInt &Value,
  9297. bool RhsConstant) {
  9298. if (S.inTemplateInstantiation())
  9299. return false;
  9300. Expr *OriginalOther = Other;
  9301. Constant = Constant->IgnoreParenImpCasts();
  9302. Other = Other->IgnoreParenImpCasts();
  9303. // Suppress warnings on tautological comparisons between values of the same
  9304. // enumeration type. There are only two ways we could warn on this:
  9305. // - If the constant is outside the range of representable values of
  9306. // the enumeration. In such a case, we should warn about the cast
  9307. // to enumeration type, not about the comparison.
  9308. // - If the constant is the maximum / minimum in-range value. For an
  9309. // enumeratin type, such comparisons can be meaningful and useful.
  9310. if (Constant->getType()->isEnumeralType() &&
  9311. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9312. return false;
  9313. // TODO: Investigate using GetExprRange() to get tighter bounds
  9314. // on the bit ranges.
  9315. QualType OtherT = Other->getType();
  9316. if (const auto *AT = OtherT->getAs<AtomicType>())
  9317. OtherT = AT->getValueType();
  9318. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9319. // Special case for ObjC BOOL on targets where its a typedef for a signed char
  9320. // (Namely, macOS).
  9321. bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
  9322. S.NSAPIObj->isObjCBOOLType(OtherT) &&
  9323. OtherT->isSpecificBuiltinType(BuiltinType::SChar);
  9324. // Whether we're treating Other as being a bool because of the form of
  9325. // expression despite it having another type (typically 'int' in C).
  9326. bool OtherIsBooleanDespiteType =
  9327. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9328. if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
  9329. OtherRange = IntRange::forBoolType();
  9330. // Determine the promoted range of the other type and see if a comparison of
  9331. // the constant against that range is tautological.
  9332. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9333. Value.isUnsigned());
  9334. auto Cmp = OtherPromotedRange.compare(Value);
  9335. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9336. if (!Result)
  9337. return false;
  9338. // Suppress the diagnostic for an in-range comparison if the constant comes
  9339. // from a macro or enumerator. We don't want to diagnose
  9340. //
  9341. // some_long_value <= INT_MAX
  9342. //
  9343. // when sizeof(int) == sizeof(long).
  9344. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9345. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9346. return false;
  9347. // If this is a comparison to an enum constant, include that
  9348. // constant in the diagnostic.
  9349. const EnumConstantDecl *ED = nullptr;
  9350. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9351. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9352. // Should be enough for uint128 (39 decimal digits)
  9353. SmallString<64> PrettySourceValue;
  9354. llvm::raw_svector_ostream OS(PrettySourceValue);
  9355. if (ED) {
  9356. OS << '\'' << *ED << "' (" << Value << ")";
  9357. } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
  9358. Constant->IgnoreParenImpCasts())) {
  9359. OS << (BL->getValue() ? "YES" : "NO");
  9360. } else {
  9361. OS << Value;
  9362. }
  9363. if (IsObjCSignedCharBool) {
  9364. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9365. S.PDiag(diag::warn_tautological_compare_objc_bool)
  9366. << OS.str() << *Result);
  9367. return true;
  9368. }
  9369. // FIXME: We use a somewhat different formatting for the in-range cases and
  9370. // cases involving boolean values for historical reasons. We should pick a
  9371. // consistent way of presenting these diagnostics.
  9372. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9373. S.DiagRuntimeBehavior(
  9374. E->getOperatorLoc(), E,
  9375. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9376. : diag::warn_tautological_bool_compare)
  9377. << OS.str() << classifyConstantValue(Constant) << OtherT
  9378. << OtherIsBooleanDespiteType << *Result
  9379. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9380. } else {
  9381. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9382. ? (HasEnumType(OriginalOther)
  9383. ? diag::warn_unsigned_enum_always_true_comparison
  9384. : diag::warn_unsigned_always_true_comparison)
  9385. : diag::warn_tautological_constant_compare;
  9386. S.Diag(E->getOperatorLoc(), Diag)
  9387. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9388. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9389. }
  9390. return true;
  9391. }
  9392. /// Analyze the operands of the given comparison. Implements the
  9393. /// fallback case from AnalyzeComparison.
  9394. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9395. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9396. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9397. }
  9398. /// Implements -Wsign-compare.
  9399. ///
  9400. /// \param E the binary operator to check for warnings
  9401. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9402. // The type the comparison is being performed in.
  9403. QualType T = E->getLHS()->getType();
  9404. // Only analyze comparison operators where both sides have been converted to
  9405. // the same type.
  9406. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9407. return AnalyzeImpConvsInComparison(S, E);
  9408. // Don't analyze value-dependent comparisons directly.
  9409. if (E->isValueDependent())
  9410. return AnalyzeImpConvsInComparison(S, E);
  9411. Expr *LHS = E->getLHS();
  9412. Expr *RHS = E->getRHS();
  9413. if (T->isIntegralType(S.Context)) {
  9414. llvm::APSInt RHSValue;
  9415. llvm::APSInt LHSValue;
  9416. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9417. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9418. // We don't care about expressions whose result is a constant.
  9419. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9420. return AnalyzeImpConvsInComparison(S, E);
  9421. // We only care about expressions where just one side is literal
  9422. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9423. // Is the constant on the RHS or LHS?
  9424. const bool RhsConstant = IsRHSIntegralLiteral;
  9425. Expr *Const = RhsConstant ? RHS : LHS;
  9426. Expr *Other = RhsConstant ? LHS : RHS;
  9427. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9428. // Check whether an integer constant comparison results in a value
  9429. // of 'true' or 'false'.
  9430. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9431. return AnalyzeImpConvsInComparison(S, E);
  9432. }
  9433. }
  9434. if (!T->hasUnsignedIntegerRepresentation()) {
  9435. // We don't do anything special if this isn't an unsigned integral
  9436. // comparison: we're only interested in integral comparisons, and
  9437. // signed comparisons only happen in cases we don't care to warn about.
  9438. return AnalyzeImpConvsInComparison(S, E);
  9439. }
  9440. LHS = LHS->IgnoreParenImpCasts();
  9441. RHS = RHS->IgnoreParenImpCasts();
  9442. if (!S.getLangOpts().CPlusPlus) {
  9443. // Avoid warning about comparison of integers with different signs when
  9444. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9445. // the type of `E`.
  9446. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9447. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9448. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9449. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9450. }
  9451. // Check to see if one of the (unmodified) operands is of different
  9452. // signedness.
  9453. Expr *signedOperand, *unsignedOperand;
  9454. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9455. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9456. "unsigned comparison between two signed integer expressions?");
  9457. signedOperand = LHS;
  9458. unsignedOperand = RHS;
  9459. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9460. signedOperand = RHS;
  9461. unsignedOperand = LHS;
  9462. } else {
  9463. return AnalyzeImpConvsInComparison(S, E);
  9464. }
  9465. // Otherwise, calculate the effective range of the signed operand.
  9466. IntRange signedRange =
  9467. GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
  9468. // Go ahead and analyze implicit conversions in the operands. Note
  9469. // that we skip the implicit conversions on both sides.
  9470. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9471. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9472. // If the signed range is non-negative, -Wsign-compare won't fire.
  9473. if (signedRange.NonNegative)
  9474. return;
  9475. // For (in)equality comparisons, if the unsigned operand is a
  9476. // constant which cannot collide with a overflowed signed operand,
  9477. // then reinterpreting the signed operand as unsigned will not
  9478. // change the result of the comparison.
  9479. if (E->isEqualityOp()) {
  9480. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9481. IntRange unsignedRange =
  9482. GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
  9483. // We should never be unable to prove that the unsigned operand is
  9484. // non-negative.
  9485. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9486. if (unsignedRange.Width < comparisonWidth)
  9487. return;
  9488. }
  9489. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9490. S.PDiag(diag::warn_mixed_sign_comparison)
  9491. << LHS->getType() << RHS->getType()
  9492. << LHS->getSourceRange() << RHS->getSourceRange());
  9493. }
  9494. /// Analyzes an attempt to assign the given value to a bitfield.
  9495. ///
  9496. /// Returns true if there was something fishy about the attempt.
  9497. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9498. SourceLocation InitLoc) {
  9499. assert(Bitfield->isBitField());
  9500. if (Bitfield->isInvalidDecl())
  9501. return false;
  9502. // White-list bool bitfields.
  9503. QualType BitfieldType = Bitfield->getType();
  9504. if (BitfieldType->isBooleanType())
  9505. return false;
  9506. if (BitfieldType->isEnumeralType()) {
  9507. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9508. // If the underlying enum type was not explicitly specified as an unsigned
  9509. // type and the enum contain only positive values, MSVC++ will cause an
  9510. // inconsistency by storing this as a signed type.
  9511. if (S.getLangOpts().CPlusPlus11 &&
  9512. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9513. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9514. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9515. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9516. << BitfieldEnumDecl->getNameAsString();
  9517. }
  9518. }
  9519. if (Bitfield->getType()->isBooleanType())
  9520. return false;
  9521. // Ignore value- or type-dependent expressions.
  9522. if (Bitfield->getBitWidth()->isValueDependent() ||
  9523. Bitfield->getBitWidth()->isTypeDependent() ||
  9524. Init->isValueDependent() ||
  9525. Init->isTypeDependent())
  9526. return false;
  9527. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9528. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9529. Expr::EvalResult Result;
  9530. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9531. Expr::SE_AllowSideEffects)) {
  9532. // The RHS is not constant. If the RHS has an enum type, make sure the
  9533. // bitfield is wide enough to hold all the values of the enum without
  9534. // truncation.
  9535. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9536. EnumDecl *ED = EnumTy->getDecl();
  9537. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9538. // Enum types are implicitly signed on Windows, so check if there are any
  9539. // negative enumerators to see if the enum was intended to be signed or
  9540. // not.
  9541. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9542. // Check for surprising sign changes when assigning enum values to a
  9543. // bitfield of different signedness. If the bitfield is signed and we
  9544. // have exactly the right number of bits to store this unsigned enum,
  9545. // suggest changing the enum to an unsigned type. This typically happens
  9546. // on Windows where unfixed enums always use an underlying type of 'int'.
  9547. unsigned DiagID = 0;
  9548. if (SignedEnum && !SignedBitfield) {
  9549. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9550. } else if (SignedBitfield && !SignedEnum &&
  9551. ED->getNumPositiveBits() == FieldWidth) {
  9552. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9553. }
  9554. if (DiagID) {
  9555. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9556. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9557. SourceRange TypeRange =
  9558. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9559. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9560. << SignedEnum << TypeRange;
  9561. }
  9562. // Compute the required bitwidth. If the enum has negative values, we need
  9563. // one more bit than the normal number of positive bits to represent the
  9564. // sign bit.
  9565. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9566. ED->getNumNegativeBits())
  9567. : ED->getNumPositiveBits();
  9568. // Check the bitwidth.
  9569. if (BitsNeeded > FieldWidth) {
  9570. Expr *WidthExpr = Bitfield->getBitWidth();
  9571. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9572. << Bitfield << ED;
  9573. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9574. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9575. }
  9576. }
  9577. return false;
  9578. }
  9579. llvm::APSInt Value = Result.Val.getInt();
  9580. unsigned OriginalWidth = Value.getBitWidth();
  9581. if (!Value.isSigned() || Value.isNegative())
  9582. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9583. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9584. OriginalWidth = Value.getMinSignedBits();
  9585. if (OriginalWidth <= FieldWidth)
  9586. return false;
  9587. // Compute the value which the bitfield will contain.
  9588. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9589. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9590. // Check whether the stored value is equal to the original value.
  9591. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9592. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9593. return false;
  9594. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9595. // therefore don't strictly fit into a signed bitfield of width 1.
  9596. if (FieldWidth == 1 && Value == 1)
  9597. return false;
  9598. std::string PrettyValue = Value.toString(10);
  9599. std::string PrettyTrunc = TruncatedValue.toString(10);
  9600. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9601. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9602. << Init->getSourceRange();
  9603. return true;
  9604. }
  9605. /// Analyze the given simple or compound assignment for warning-worthy
  9606. /// operations.
  9607. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9608. // Just recurse on the LHS.
  9609. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9610. // We want to recurse on the RHS as normal unless we're assigning to
  9611. // a bitfield.
  9612. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9613. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9614. E->getOperatorLoc())) {
  9615. // Recurse, ignoring any implicit conversions on the RHS.
  9616. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9617. E->getOperatorLoc());
  9618. }
  9619. }
  9620. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9621. // Diagnose implicitly sequentially-consistent atomic assignment.
  9622. if (E->getLHS()->getType()->isAtomicType())
  9623. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9624. }
  9625. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9626. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9627. SourceLocation CContext, unsigned diag,
  9628. bool pruneControlFlow = false) {
  9629. if (pruneControlFlow) {
  9630. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9631. S.PDiag(diag)
  9632. << SourceType << T << E->getSourceRange()
  9633. << SourceRange(CContext));
  9634. return;
  9635. }
  9636. S.Diag(E->getExprLoc(), diag)
  9637. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9638. }
  9639. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9640. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9641. SourceLocation CContext,
  9642. unsigned diag, bool pruneControlFlow = false) {
  9643. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9644. }
  9645. /// Diagnose an implicit cast from a floating point value to an integer value.
  9646. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9647. SourceLocation CContext) {
  9648. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9649. const bool PruneWarnings = S.inTemplateInstantiation();
  9650. Expr *InnerE = E->IgnoreParenImpCasts();
  9651. // We also want to warn on, e.g., "int i = -1.234"
  9652. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9653. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9654. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9655. const bool IsLiteral =
  9656. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9657. llvm::APFloat Value(0.0);
  9658. bool IsConstant =
  9659. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9660. if (!IsConstant) {
  9661. return DiagnoseImpCast(S, E, T, CContext,
  9662. diag::warn_impcast_float_integer, PruneWarnings);
  9663. }
  9664. bool isExact = false;
  9665. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9666. T->hasUnsignedIntegerRepresentation());
  9667. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9668. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9669. if (Result == llvm::APFloat::opOK && isExact) {
  9670. if (IsLiteral) return;
  9671. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9672. PruneWarnings);
  9673. }
  9674. // Conversion of a floating-point value to a non-bool integer where the
  9675. // integral part cannot be represented by the integer type is undefined.
  9676. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9677. return DiagnoseImpCast(
  9678. S, E, T, CContext,
  9679. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9680. : diag::warn_impcast_float_to_integer_out_of_range,
  9681. PruneWarnings);
  9682. unsigned DiagID = 0;
  9683. if (IsLiteral) {
  9684. // Warn on floating point literal to integer.
  9685. DiagID = diag::warn_impcast_literal_float_to_integer;
  9686. } else if (IntegerValue == 0) {
  9687. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9688. return DiagnoseImpCast(S, E, T, CContext,
  9689. diag::warn_impcast_float_integer, PruneWarnings);
  9690. }
  9691. // Warn on non-zero to zero conversion.
  9692. DiagID = diag::warn_impcast_float_to_integer_zero;
  9693. } else {
  9694. if (IntegerValue.isUnsigned()) {
  9695. if (!IntegerValue.isMaxValue()) {
  9696. return DiagnoseImpCast(S, E, T, CContext,
  9697. diag::warn_impcast_float_integer, PruneWarnings);
  9698. }
  9699. } else { // IntegerValue.isSigned()
  9700. if (!IntegerValue.isMaxSignedValue() &&
  9701. !IntegerValue.isMinSignedValue()) {
  9702. return DiagnoseImpCast(S, E, T, CContext,
  9703. diag::warn_impcast_float_integer, PruneWarnings);
  9704. }
  9705. }
  9706. // Warn on evaluatable floating point expression to integer conversion.
  9707. DiagID = diag::warn_impcast_float_to_integer;
  9708. }
  9709. // FIXME: Force the precision of the source value down so we don't print
  9710. // digits which are usually useless (we don't really care here if we
  9711. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9712. // would automatically print the shortest representation, but it's a bit
  9713. // tricky to implement.
  9714. SmallString<16> PrettySourceValue;
  9715. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9716. precision = (precision * 59 + 195) / 196;
  9717. Value.toString(PrettySourceValue, precision);
  9718. SmallString<16> PrettyTargetValue;
  9719. if (IsBool)
  9720. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9721. else
  9722. IntegerValue.toString(PrettyTargetValue);
  9723. if (PruneWarnings) {
  9724. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9725. S.PDiag(DiagID)
  9726. << E->getType() << T.getUnqualifiedType()
  9727. << PrettySourceValue << PrettyTargetValue
  9728. << E->getSourceRange() << SourceRange(CContext));
  9729. } else {
  9730. S.Diag(E->getExprLoc(), DiagID)
  9731. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9732. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9733. }
  9734. }
  9735. /// Analyze the given compound assignment for the possible losing of
  9736. /// floating-point precision.
  9737. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9738. assert(isa<CompoundAssignOperator>(E) &&
  9739. "Must be compound assignment operation");
  9740. // Recurse on the LHS and RHS in here
  9741. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9742. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9743. if (E->getLHS()->getType()->isAtomicType())
  9744. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9745. // Now check the outermost expression
  9746. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9747. const auto *RBT = cast<CompoundAssignOperator>(E)
  9748. ->getComputationResultType()
  9749. ->getAs<BuiltinType>();
  9750. // The below checks assume source is floating point.
  9751. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9752. // If source is floating point but target is an integer.
  9753. if (ResultBT->isInteger())
  9754. return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
  9755. E->getExprLoc(), diag::warn_impcast_float_integer);
  9756. if (!ResultBT->isFloatingPoint())
  9757. return;
  9758. // If both source and target are floating points, warn about losing precision.
  9759. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  9760. QualType(ResultBT, 0), QualType(RBT, 0));
  9761. if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9762. // warn about dropping FP rank.
  9763. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9764. diag::warn_impcast_float_result_precision);
  9765. }
  9766. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9767. IntRange Range) {
  9768. if (!Range.Width) return "0";
  9769. llvm::APSInt ValueInRange = Value;
  9770. ValueInRange.setIsSigned(!Range.NonNegative);
  9771. ValueInRange = ValueInRange.trunc(Range.Width);
  9772. return ValueInRange.toString(10);
  9773. }
  9774. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9775. if (!isa<ImplicitCastExpr>(Ex))
  9776. return false;
  9777. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9778. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9779. const Type *Source =
  9780. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9781. if (Target->isDependentType())
  9782. return false;
  9783. const BuiltinType *FloatCandidateBT =
  9784. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9785. const Type *BoolCandidateType = ToBool ? Target : Source;
  9786. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9787. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9788. }
  9789. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9790. SourceLocation CC) {
  9791. unsigned NumArgs = TheCall->getNumArgs();
  9792. for (unsigned i = 0; i < NumArgs; ++i) {
  9793. Expr *CurrA = TheCall->getArg(i);
  9794. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9795. continue;
  9796. bool IsSwapped = ((i > 0) &&
  9797. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9798. IsSwapped |= ((i < (NumArgs - 1)) &&
  9799. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9800. if (IsSwapped) {
  9801. // Warn on this floating-point to bool conversion.
  9802. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9803. CurrA->getType(), CC,
  9804. diag::warn_impcast_floating_point_to_bool);
  9805. }
  9806. }
  9807. }
  9808. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9809. SourceLocation CC) {
  9810. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9811. E->getExprLoc()))
  9812. return;
  9813. // Don't warn on functions which have return type nullptr_t.
  9814. if (isa<CallExpr>(E))
  9815. return;
  9816. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9817. const Expr::NullPointerConstantKind NullKind =
  9818. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9819. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9820. return;
  9821. // Return if target type is a safe conversion.
  9822. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9823. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9824. return;
  9825. SourceLocation Loc = E->getSourceRange().getBegin();
  9826. // Venture through the macro stacks to get to the source of macro arguments.
  9827. // The new location is a better location than the complete location that was
  9828. // passed in.
  9829. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9830. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9831. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9832. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9833. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9834. Loc, S.SourceMgr, S.getLangOpts());
  9835. if (MacroName == "NULL")
  9836. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9837. }
  9838. // Only warn if the null and context location are in the same macro expansion.
  9839. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9840. return;
  9841. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9842. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9843. << FixItHint::CreateReplacement(Loc,
  9844. S.getFixItZeroLiteralForType(T, Loc));
  9845. }
  9846. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9847. ObjCArrayLiteral *ArrayLiteral);
  9848. static void
  9849. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9850. ObjCDictionaryLiteral *DictionaryLiteral);
  9851. /// Check a single element within a collection literal against the
  9852. /// target element type.
  9853. static void checkObjCCollectionLiteralElement(Sema &S,
  9854. QualType TargetElementType,
  9855. Expr *Element,
  9856. unsigned ElementKind) {
  9857. // Skip a bitcast to 'id' or qualified 'id'.
  9858. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9859. if (ICE->getCastKind() == CK_BitCast &&
  9860. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9861. Element = ICE->getSubExpr();
  9862. }
  9863. QualType ElementType = Element->getType();
  9864. ExprResult ElementResult(Element);
  9865. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9866. S.CheckSingleAssignmentConstraints(TargetElementType,
  9867. ElementResult,
  9868. false, false)
  9869. != Sema::Compatible) {
  9870. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9871. << ElementType << ElementKind << TargetElementType
  9872. << Element->getSourceRange();
  9873. }
  9874. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9875. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9876. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9877. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9878. }
  9879. /// Check an Objective-C array literal being converted to the given
  9880. /// target type.
  9881. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9882. ObjCArrayLiteral *ArrayLiteral) {
  9883. if (!S.NSArrayDecl)
  9884. return;
  9885. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9886. if (!TargetObjCPtr)
  9887. return;
  9888. if (TargetObjCPtr->isUnspecialized() ||
  9889. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9890. != S.NSArrayDecl->getCanonicalDecl())
  9891. return;
  9892. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9893. if (TypeArgs.size() != 1)
  9894. return;
  9895. QualType TargetElementType = TypeArgs[0];
  9896. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9897. checkObjCCollectionLiteralElement(S, TargetElementType,
  9898. ArrayLiteral->getElement(I),
  9899. 0);
  9900. }
  9901. }
  9902. /// Check an Objective-C dictionary literal being converted to the given
  9903. /// target type.
  9904. static void
  9905. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9906. ObjCDictionaryLiteral *DictionaryLiteral) {
  9907. if (!S.NSDictionaryDecl)
  9908. return;
  9909. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9910. if (!TargetObjCPtr)
  9911. return;
  9912. if (TargetObjCPtr->isUnspecialized() ||
  9913. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9914. != S.NSDictionaryDecl->getCanonicalDecl())
  9915. return;
  9916. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9917. if (TypeArgs.size() != 2)
  9918. return;
  9919. QualType TargetKeyType = TypeArgs[0];
  9920. QualType TargetObjectType = TypeArgs[1];
  9921. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9922. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9923. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9924. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9925. }
  9926. }
  9927. // Helper function to filter out cases for constant width constant conversion.
  9928. // Don't warn on char array initialization or for non-decimal values.
  9929. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9930. SourceLocation CC) {
  9931. // If initializing from a constant, and the constant starts with '0',
  9932. // then it is a binary, octal, or hexadecimal. Allow these constants
  9933. // to fill all the bits, even if there is a sign change.
  9934. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9935. const char FirstLiteralCharacter =
  9936. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9937. if (FirstLiteralCharacter == '0')
  9938. return false;
  9939. }
  9940. // If the CC location points to a '{', and the type is char, then assume
  9941. // assume it is an array initialization.
  9942. if (CC.isValid() && T->isCharType()) {
  9943. const char FirstContextCharacter =
  9944. S.getSourceManager().getCharacterData(CC)[0];
  9945. if (FirstContextCharacter == '{')
  9946. return false;
  9947. }
  9948. return true;
  9949. }
  9950. static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
  9951. return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
  9952. S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
  9953. }
  9954. static void
  9955. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9956. bool *ICContext = nullptr) {
  9957. if (E->isTypeDependent() || E->isValueDependent()) return;
  9958. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9959. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9960. if (Source == Target) return;
  9961. if (Target->isDependentType()) return;
  9962. // If the conversion context location is invalid don't complain. We also
  9963. // don't want to emit a warning if the issue occurs from the expansion of
  9964. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9965. // delay this check as long as possible. Once we detect we are in that
  9966. // scenario, we just return.
  9967. if (CC.isInvalid())
  9968. return;
  9969. if (Source->isAtomicType())
  9970. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9971. // Diagnose implicit casts to bool.
  9972. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9973. if (isa<StringLiteral>(E))
  9974. // Warn on string literal to bool. Checks for string literals in logical
  9975. // and expressions, for instance, assert(0 && "error here"), are
  9976. // prevented by a check in AnalyzeImplicitConversions().
  9977. return DiagnoseImpCast(S, E, T, CC,
  9978. diag::warn_impcast_string_literal_to_bool);
  9979. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9980. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9981. // This covers the literal expressions that evaluate to Objective-C
  9982. // objects.
  9983. return DiagnoseImpCast(S, E, T, CC,
  9984. diag::warn_impcast_objective_c_literal_to_bool);
  9985. }
  9986. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9987. // Warn on pointer to bool conversion that is always true.
  9988. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9989. SourceRange(CC));
  9990. }
  9991. }
  9992. // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
  9993. // is a typedef for signed char (macOS), then that constant value has to be 1
  9994. // or 0.
  9995. if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
  9996. Expr::EvalResult Result;
  9997. if (E->EvaluateAsInt(Result, S.getASTContext(),
  9998. Expr::SE_AllowSideEffects) &&
  9999. Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
  10000. auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool)
  10001. << Result.Val.getInt().toString(10);
  10002. Expr *Ignored = E->IgnoreImplicit();
  10003. bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
  10004. isa<BinaryOperator>(Ignored) ||
  10005. isa<CXXOperatorCallExpr>(Ignored);
  10006. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  10007. if (NeedsParens)
  10008. Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
  10009. << FixItHint::CreateInsertion(EndLoc, ")");
  10010. Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
  10011. return;
  10012. }
  10013. }
  10014. // Check implicit casts from Objective-C collection literals to specialized
  10015. // collection types, e.g., NSArray<NSString *> *.
  10016. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  10017. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  10018. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  10019. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  10020. // Strip vector types.
  10021. if (isa<VectorType>(Source)) {
  10022. if (!isa<VectorType>(Target)) {
  10023. if (S.SourceMgr.isInSystemMacro(CC))
  10024. return;
  10025. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  10026. }
  10027. // If the vector cast is cast between two vectors of the same size, it is
  10028. // a bitcast, not a conversion.
  10029. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  10030. return;
  10031. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  10032. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  10033. }
  10034. if (auto VecTy = dyn_cast<VectorType>(Target))
  10035. Target = VecTy->getElementType().getTypePtr();
  10036. // Strip complex types.
  10037. if (isa<ComplexType>(Source)) {
  10038. if (!isa<ComplexType>(Target)) {
  10039. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  10040. return;
  10041. return DiagnoseImpCast(S, E, T, CC,
  10042. S.getLangOpts().CPlusPlus
  10043. ? diag::err_impcast_complex_scalar
  10044. : diag::warn_impcast_complex_scalar);
  10045. }
  10046. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  10047. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  10048. }
  10049. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  10050. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  10051. // If the source is floating point...
  10052. if (SourceBT && SourceBT->isFloatingPoint()) {
  10053. // ...and the target is floating point...
  10054. if (TargetBT && TargetBT->isFloatingPoint()) {
  10055. // ...then warn if we're dropping FP rank.
  10056. int Order = S.getASTContext().getFloatingTypeSemanticOrder(
  10057. QualType(SourceBT, 0), QualType(TargetBT, 0));
  10058. if (Order > 0) {
  10059. // Don't warn about float constants that are precisely
  10060. // representable in the target type.
  10061. Expr::EvalResult result;
  10062. if (E->EvaluateAsRValue(result, S.Context)) {
  10063. // Value might be a float, a float vector, or a float complex.
  10064. if (IsSameFloatAfterCast(result.Val,
  10065. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  10066. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  10067. return;
  10068. }
  10069. if (S.SourceMgr.isInSystemMacro(CC))
  10070. return;
  10071. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  10072. }
  10073. // ... or possibly if we're increasing rank, too
  10074. else if (Order < 0) {
  10075. if (S.SourceMgr.isInSystemMacro(CC))
  10076. return;
  10077. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  10078. }
  10079. return;
  10080. }
  10081. // If the target is integral, always warn.
  10082. if (TargetBT && TargetBT->isInteger()) {
  10083. if (S.SourceMgr.isInSystemMacro(CC))
  10084. return;
  10085. DiagnoseFloatingImpCast(S, E, T, CC);
  10086. }
  10087. // Detect the case where a call result is converted from floating-point to
  10088. // to bool, and the final argument to the call is converted from bool, to
  10089. // discover this typo:
  10090. //
  10091. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  10092. //
  10093. // FIXME: This is an incredibly special case; is there some more general
  10094. // way to detect this class of misplaced-parentheses bug?
  10095. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  10096. // Check last argument of function call to see if it is an
  10097. // implicit cast from a type matching the type the result
  10098. // is being cast to.
  10099. CallExpr *CEx = cast<CallExpr>(E);
  10100. if (unsigned NumArgs = CEx->getNumArgs()) {
  10101. Expr *LastA = CEx->getArg(NumArgs - 1);
  10102. Expr *InnerE = LastA->IgnoreParenImpCasts();
  10103. if (isa<ImplicitCastExpr>(LastA) &&
  10104. InnerE->getType()->isBooleanType()) {
  10105. // Warn on this floating-point to bool conversion
  10106. DiagnoseImpCast(S, E, T, CC,
  10107. diag::warn_impcast_floating_point_to_bool);
  10108. }
  10109. }
  10110. }
  10111. return;
  10112. }
  10113. // Valid casts involving fixed point types should be accounted for here.
  10114. if (Source->isFixedPointType()) {
  10115. if (Target->isUnsaturatedFixedPointType()) {
  10116. Expr::EvalResult Result;
  10117. if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
  10118. S.isConstantEvaluated())) {
  10119. APFixedPoint Value = Result.Val.getFixedPoint();
  10120. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  10121. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  10122. if (Value > MaxVal || Value < MinVal) {
  10123. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10124. S.PDiag(diag::warn_impcast_fixed_point_range)
  10125. << Value.toString() << T
  10126. << E->getSourceRange()
  10127. << clang::SourceRange(CC));
  10128. return;
  10129. }
  10130. }
  10131. } else if (Target->isIntegerType()) {
  10132. Expr::EvalResult Result;
  10133. if (!S.isConstantEvaluated() &&
  10134. E->EvaluateAsFixedPoint(Result, S.Context,
  10135. Expr::SE_AllowSideEffects)) {
  10136. APFixedPoint FXResult = Result.Val.getFixedPoint();
  10137. bool Overflowed;
  10138. llvm::APSInt IntResult = FXResult.convertToInt(
  10139. S.Context.getIntWidth(T),
  10140. Target->isSignedIntegerOrEnumerationType(), &Overflowed);
  10141. if (Overflowed) {
  10142. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10143. S.PDiag(diag::warn_impcast_fixed_point_range)
  10144. << FXResult.toString() << T
  10145. << E->getSourceRange()
  10146. << clang::SourceRange(CC));
  10147. return;
  10148. }
  10149. }
  10150. }
  10151. } else if (Target->isUnsaturatedFixedPointType()) {
  10152. if (Source->isIntegerType()) {
  10153. Expr::EvalResult Result;
  10154. if (!S.isConstantEvaluated() &&
  10155. E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  10156. llvm::APSInt Value = Result.Val.getInt();
  10157. bool Overflowed;
  10158. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10159. Value, S.Context.getFixedPointSemantics(T), &Overflowed);
  10160. if (Overflowed) {
  10161. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  10162. S.PDiag(diag::warn_impcast_fixed_point_range)
  10163. << Value.toString(/*Radix=*/10) << T
  10164. << E->getSourceRange()
  10165. << clang::SourceRange(CC));
  10166. return;
  10167. }
  10168. }
  10169. }
  10170. }
  10171. DiagnoseNullConversion(S, E, T, CC);
  10172. S.DiscardMisalignedMemberAddress(Target, E);
  10173. if (!Source->isIntegerType() || !Target->isIntegerType())
  10174. return;
  10175. // TODO: remove this early return once the false positives for constant->bool
  10176. // in templates, macros, etc, are reduced or removed.
  10177. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  10178. return;
  10179. IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
  10180. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  10181. if (SourceRange.Width > TargetRange.Width) {
  10182. // If the source is a constant, use a default-on diagnostic.
  10183. // TODO: this should happen for bitfield stores, too.
  10184. Expr::EvalResult Result;
  10185. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
  10186. S.isConstantEvaluated())) {
  10187. llvm::APSInt Value(32);
  10188. Value = Result.Val.getInt();
  10189. if (S.SourceMgr.isInSystemMacro(CC))
  10190. return;
  10191. std::string PrettySourceValue = Value.toString(10);
  10192. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10193. S.DiagRuntimeBehavior(
  10194. E->getExprLoc(), E,
  10195. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10196. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10197. << E->getSourceRange() << clang::SourceRange(CC));
  10198. return;
  10199. }
  10200. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  10201. if (S.SourceMgr.isInSystemMacro(CC))
  10202. return;
  10203. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  10204. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  10205. /* pruneControlFlow */ true);
  10206. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  10207. }
  10208. if (TargetRange.Width > SourceRange.Width) {
  10209. if (auto *UO = dyn_cast<UnaryOperator>(E))
  10210. if (UO->getOpcode() == UO_Minus)
  10211. if (Source->isUnsignedIntegerType()) {
  10212. if (Target->isUnsignedIntegerType())
  10213. return DiagnoseImpCast(S, E, T, CC,
  10214. diag::warn_impcast_high_order_zero_bits);
  10215. if (Target->isSignedIntegerType())
  10216. return DiagnoseImpCast(S, E, T, CC,
  10217. diag::warn_impcast_nonnegative_result);
  10218. }
  10219. }
  10220. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  10221. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  10222. // Warn when doing a signed to signed conversion, warn if the positive
  10223. // source value is exactly the width of the target type, which will
  10224. // cause a negative value to be stored.
  10225. Expr::EvalResult Result;
  10226. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  10227. !S.SourceMgr.isInSystemMacro(CC)) {
  10228. llvm::APSInt Value = Result.Val.getInt();
  10229. if (isSameWidthConstantConversion(S, E, T, CC)) {
  10230. std::string PrettySourceValue = Value.toString(10);
  10231. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  10232. S.DiagRuntimeBehavior(
  10233. E->getExprLoc(), E,
  10234. S.PDiag(diag::warn_impcast_integer_precision_constant)
  10235. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  10236. << E->getSourceRange() << clang::SourceRange(CC));
  10237. return;
  10238. }
  10239. }
  10240. // Fall through for non-constants to give a sign conversion warning.
  10241. }
  10242. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  10243. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  10244. SourceRange.Width == TargetRange.Width)) {
  10245. if (S.SourceMgr.isInSystemMacro(CC))
  10246. return;
  10247. unsigned DiagID = diag::warn_impcast_integer_sign;
  10248. // Traditionally, gcc has warned about this under -Wsign-compare.
  10249. // We also want to warn about it in -Wconversion.
  10250. // So if -Wconversion is off, use a completely identical diagnostic
  10251. // in the sign-compare group.
  10252. // The conditional-checking code will
  10253. if (ICContext) {
  10254. DiagID = diag::warn_impcast_integer_sign_conditional;
  10255. *ICContext = true;
  10256. }
  10257. return DiagnoseImpCast(S, E, T, CC, DiagID);
  10258. }
  10259. // Diagnose conversions between different enumeration types.
  10260. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  10261. // type, to give us better diagnostics.
  10262. QualType SourceType = E->getType();
  10263. if (!S.getLangOpts().CPlusPlus) {
  10264. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10265. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  10266. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  10267. SourceType = S.Context.getTypeDeclType(Enum);
  10268. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  10269. }
  10270. }
  10271. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  10272. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  10273. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  10274. TargetEnum->getDecl()->hasNameForLinkage() &&
  10275. SourceEnum != TargetEnum) {
  10276. if (S.SourceMgr.isInSystemMacro(CC))
  10277. return;
  10278. return DiagnoseImpCast(S, E, SourceType, T, CC,
  10279. diag::warn_impcast_different_enum_types);
  10280. }
  10281. }
  10282. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10283. SourceLocation CC, QualType T);
  10284. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  10285. SourceLocation CC, bool &ICContext) {
  10286. E = E->IgnoreParenImpCasts();
  10287. if (isa<ConditionalOperator>(E))
  10288. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  10289. AnalyzeImplicitConversions(S, E, CC);
  10290. if (E->getType() != T)
  10291. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  10292. }
  10293. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  10294. SourceLocation CC, QualType T) {
  10295. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  10296. bool Suspicious = false;
  10297. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  10298. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  10299. // If -Wconversion would have warned about either of the candidates
  10300. // for a signedness conversion to the context type...
  10301. if (!Suspicious) return;
  10302. // ...but it's currently ignored...
  10303. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  10304. return;
  10305. // ...then check whether it would have warned about either of the
  10306. // candidates for a signedness conversion to the condition type.
  10307. if (E->getType() == T) return;
  10308. Suspicious = false;
  10309. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  10310. E->getType(), CC, &Suspicious);
  10311. if (!Suspicious)
  10312. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  10313. E->getType(), CC, &Suspicious);
  10314. }
  10315. /// Check conversion of given expression to boolean.
  10316. /// Input argument E is a logical expression.
  10317. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  10318. if (S.getLangOpts().Bool)
  10319. return;
  10320. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10321. return;
  10322. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10323. }
  10324. /// AnalyzeImplicitConversions - Find and report any interesting
  10325. /// implicit conversions in the given expression. There are a couple
  10326. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10327. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  10328. SourceLocation CC) {
  10329. QualType T = OrigE->getType();
  10330. Expr *E = OrigE->IgnoreParenImpCasts();
  10331. if (E->isTypeDependent() || E->isValueDependent())
  10332. return;
  10333. // For conditional operators, we analyze the arguments as if they
  10334. // were being fed directly into the output.
  10335. if (isa<ConditionalOperator>(E)) {
  10336. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10337. CheckConditionalOperator(S, CO, CC, T);
  10338. return;
  10339. }
  10340. // Check implicit argument conversions for function calls.
  10341. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10342. CheckImplicitArgumentConversions(S, Call, CC);
  10343. // Go ahead and check any implicit conversions we might have skipped.
  10344. // The non-canonical typecheck is just an optimization;
  10345. // CheckImplicitConversion will filter out dead implicit conversions.
  10346. if (E->getType() != T)
  10347. CheckImplicitConversion(S, E, T, CC);
  10348. // Now continue drilling into this expression.
  10349. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10350. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10351. // as transitive children.
  10352. // FIXME: Use a more uniform representation for this.
  10353. for (auto *SE : POE->semantics())
  10354. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10355. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  10356. }
  10357. // Skip past explicit casts.
  10358. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10359. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10360. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10361. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10362. return AnalyzeImplicitConversions(S, E, CC);
  10363. }
  10364. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10365. // Do a somewhat different check with comparison operators.
  10366. if (BO->isComparisonOp())
  10367. return AnalyzeComparison(S, BO);
  10368. // And with simple assignments.
  10369. if (BO->getOpcode() == BO_Assign)
  10370. return AnalyzeAssignment(S, BO);
  10371. // And with compound assignments.
  10372. if (BO->isAssignmentOp())
  10373. return AnalyzeCompoundAssignment(S, BO);
  10374. }
  10375. // These break the otherwise-useful invariant below. Fortunately,
  10376. // we don't really need to recurse into them, because any internal
  10377. // expressions should have been analyzed already when they were
  10378. // built into statements.
  10379. if (isa<StmtExpr>(E)) return;
  10380. // Don't descend into unevaluated contexts.
  10381. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10382. // Now just recurse over the expression's children.
  10383. CC = E->getExprLoc();
  10384. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10385. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10386. for (Stmt *SubStmt : E->children()) {
  10387. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10388. if (!ChildExpr)
  10389. continue;
  10390. if (IsLogicalAndOperator &&
  10391. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10392. // Ignore checking string literals that are in logical and operators.
  10393. // This is a common pattern for asserts.
  10394. continue;
  10395. AnalyzeImplicitConversions(S, ChildExpr, CC);
  10396. }
  10397. if (BO && BO->isLogicalOp()) {
  10398. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10399. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10400. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10401. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10402. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10403. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10404. }
  10405. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10406. if (U->getOpcode() == UO_LNot) {
  10407. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10408. } else if (U->getOpcode() != UO_AddrOf) {
  10409. if (U->getSubExpr()->getType()->isAtomicType())
  10410. S.Diag(U->getSubExpr()->getBeginLoc(),
  10411. diag::warn_atomic_implicit_seq_cst);
  10412. }
  10413. }
  10414. }
  10415. /// Diagnose integer type and any valid implicit conversion to it.
  10416. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10417. // Taking into account implicit conversions,
  10418. // allow any integer.
  10419. if (!E->getType()->isIntegerType()) {
  10420. S.Diag(E->getBeginLoc(),
  10421. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10422. return true;
  10423. }
  10424. // Potentially emit standard warnings for implicit conversions if enabled
  10425. // using -Wconversion.
  10426. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10427. return false;
  10428. }
  10429. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10430. // Returns true when emitting a warning about taking the address of a reference.
  10431. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10432. const PartialDiagnostic &PD) {
  10433. E = E->IgnoreParenImpCasts();
  10434. const FunctionDecl *FD = nullptr;
  10435. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10436. if (!DRE->getDecl()->getType()->isReferenceType())
  10437. return false;
  10438. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10439. if (!M->getMemberDecl()->getType()->isReferenceType())
  10440. return false;
  10441. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10442. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10443. return false;
  10444. FD = Call->getDirectCallee();
  10445. } else {
  10446. return false;
  10447. }
  10448. SemaRef.Diag(E->getExprLoc(), PD);
  10449. // If possible, point to location of function.
  10450. if (FD) {
  10451. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10452. }
  10453. return true;
  10454. }
  10455. // Returns true if the SourceLocation is expanded from any macro body.
  10456. // Returns false if the SourceLocation is invalid, is from not in a macro
  10457. // expansion, or is from expanded from a top-level macro argument.
  10458. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10459. if (Loc.isInvalid())
  10460. return false;
  10461. while (Loc.isMacroID()) {
  10462. if (SM.isMacroBodyExpansion(Loc))
  10463. return true;
  10464. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10465. }
  10466. return false;
  10467. }
  10468. /// Diagnose pointers that are always non-null.
  10469. /// \param E the expression containing the pointer
  10470. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10471. /// compared to a null pointer
  10472. /// \param IsEqual True when the comparison is equal to a null pointer
  10473. /// \param Range Extra SourceRange to highlight in the diagnostic
  10474. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10475. Expr::NullPointerConstantKind NullKind,
  10476. bool IsEqual, SourceRange Range) {
  10477. if (!E)
  10478. return;
  10479. // Don't warn inside macros.
  10480. if (E->getExprLoc().isMacroID()) {
  10481. const SourceManager &SM = getSourceManager();
  10482. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10483. IsInAnyMacroBody(SM, Range.getBegin()))
  10484. return;
  10485. }
  10486. E = E->IgnoreImpCasts();
  10487. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10488. if (isa<CXXThisExpr>(E)) {
  10489. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10490. : diag::warn_this_bool_conversion;
  10491. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10492. return;
  10493. }
  10494. bool IsAddressOf = false;
  10495. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10496. if (UO->getOpcode() != UO_AddrOf)
  10497. return;
  10498. IsAddressOf = true;
  10499. E = UO->getSubExpr();
  10500. }
  10501. if (IsAddressOf) {
  10502. unsigned DiagID = IsCompare
  10503. ? diag::warn_address_of_reference_null_compare
  10504. : diag::warn_address_of_reference_bool_conversion;
  10505. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10506. << IsEqual;
  10507. if (CheckForReference(*this, E, PD)) {
  10508. return;
  10509. }
  10510. }
  10511. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10512. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10513. std::string Str;
  10514. llvm::raw_string_ostream S(Str);
  10515. E->printPretty(S, nullptr, getPrintingPolicy());
  10516. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10517. : diag::warn_cast_nonnull_to_bool;
  10518. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10519. << E->getSourceRange() << Range << IsEqual;
  10520. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10521. };
  10522. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10523. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10524. if (auto *Callee = Call->getDirectCallee()) {
  10525. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10526. ComplainAboutNonnullParamOrCall(A);
  10527. return;
  10528. }
  10529. }
  10530. }
  10531. // Expect to find a single Decl. Skip anything more complicated.
  10532. ValueDecl *D = nullptr;
  10533. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10534. D = R->getDecl();
  10535. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10536. D = M->getMemberDecl();
  10537. }
  10538. // Weak Decls can be null.
  10539. if (!D || D->isWeak())
  10540. return;
  10541. // Check for parameter decl with nonnull attribute
  10542. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10543. if (getCurFunction() &&
  10544. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10545. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10546. ComplainAboutNonnullParamOrCall(A);
  10547. return;
  10548. }
  10549. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10550. // Skip function template not specialized yet.
  10551. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10552. return;
  10553. auto ParamIter = llvm::find(FD->parameters(), PV);
  10554. assert(ParamIter != FD->param_end());
  10555. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10556. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10557. if (!NonNull->args_size()) {
  10558. ComplainAboutNonnullParamOrCall(NonNull);
  10559. return;
  10560. }
  10561. for (const ParamIdx &ArgNo : NonNull->args()) {
  10562. if (ArgNo.getASTIndex() == ParamNo) {
  10563. ComplainAboutNonnullParamOrCall(NonNull);
  10564. return;
  10565. }
  10566. }
  10567. }
  10568. }
  10569. }
  10570. }
  10571. QualType T = D->getType();
  10572. const bool IsArray = T->isArrayType();
  10573. const bool IsFunction = T->isFunctionType();
  10574. // Address of function is used to silence the function warning.
  10575. if (IsAddressOf && IsFunction) {
  10576. return;
  10577. }
  10578. // Found nothing.
  10579. if (!IsAddressOf && !IsFunction && !IsArray)
  10580. return;
  10581. // Pretty print the expression for the diagnostic.
  10582. std::string Str;
  10583. llvm::raw_string_ostream S(Str);
  10584. E->printPretty(S, nullptr, getPrintingPolicy());
  10585. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10586. : diag::warn_impcast_pointer_to_bool;
  10587. enum {
  10588. AddressOf,
  10589. FunctionPointer,
  10590. ArrayPointer
  10591. } DiagType;
  10592. if (IsAddressOf)
  10593. DiagType = AddressOf;
  10594. else if (IsFunction)
  10595. DiagType = FunctionPointer;
  10596. else if (IsArray)
  10597. DiagType = ArrayPointer;
  10598. else
  10599. llvm_unreachable("Could not determine diagnostic.");
  10600. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10601. << Range << IsEqual;
  10602. if (!IsFunction)
  10603. return;
  10604. // Suggest '&' to silence the function warning.
  10605. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10606. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10607. // Check to see if '()' fixit should be emitted.
  10608. QualType ReturnType;
  10609. UnresolvedSet<4> NonTemplateOverloads;
  10610. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10611. if (ReturnType.isNull())
  10612. return;
  10613. if (IsCompare) {
  10614. // There are two cases here. If there is null constant, the only suggest
  10615. // for a pointer return type. If the null is 0, then suggest if the return
  10616. // type is a pointer or an integer type.
  10617. if (!ReturnType->isPointerType()) {
  10618. if (NullKind == Expr::NPCK_ZeroExpression ||
  10619. NullKind == Expr::NPCK_ZeroLiteral) {
  10620. if (!ReturnType->isIntegerType())
  10621. return;
  10622. } else {
  10623. return;
  10624. }
  10625. }
  10626. } else { // !IsCompare
  10627. // For function to bool, only suggest if the function pointer has bool
  10628. // return type.
  10629. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10630. return;
  10631. }
  10632. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10633. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10634. }
  10635. /// Diagnoses "dangerous" implicit conversions within the given
  10636. /// expression (which is a full expression). Implements -Wconversion
  10637. /// and -Wsign-compare.
  10638. ///
  10639. /// \param CC the "context" location of the implicit conversion, i.e.
  10640. /// the most location of the syntactic entity requiring the implicit
  10641. /// conversion
  10642. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10643. // Don't diagnose in unevaluated contexts.
  10644. if (isUnevaluatedContext())
  10645. return;
  10646. // Don't diagnose for value- or type-dependent expressions.
  10647. if (E->isTypeDependent() || E->isValueDependent())
  10648. return;
  10649. // Check for array bounds violations in cases where the check isn't triggered
  10650. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10651. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10652. CheckArrayAccess(E);
  10653. // This is not the right CC for (e.g.) a variable initialization.
  10654. AnalyzeImplicitConversions(*this, E, CC);
  10655. }
  10656. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10657. /// Input argument E is a logical expression.
  10658. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10659. ::CheckBoolLikeConversion(*this, E, CC);
  10660. }
  10661. /// Diagnose when expression is an integer constant expression and its evaluation
  10662. /// results in integer overflow
  10663. void Sema::CheckForIntOverflow (Expr *E) {
  10664. // Use a work list to deal with nested struct initializers.
  10665. SmallVector<Expr *, 2> Exprs(1, E);
  10666. do {
  10667. Expr *OriginalE = Exprs.pop_back_val();
  10668. Expr *E = OriginalE->IgnoreParenCasts();
  10669. if (isa<BinaryOperator>(E)) {
  10670. E->EvaluateForOverflow(Context);
  10671. continue;
  10672. }
  10673. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10674. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10675. else if (isa<ObjCBoxedExpr>(OriginalE))
  10676. E->EvaluateForOverflow(Context);
  10677. else if (auto Call = dyn_cast<CallExpr>(E))
  10678. Exprs.append(Call->arg_begin(), Call->arg_end());
  10679. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10680. Exprs.append(Message->arg_begin(), Message->arg_end());
  10681. } while (!Exprs.empty());
  10682. }
  10683. namespace {
  10684. /// Visitor for expressions which looks for unsequenced operations on the
  10685. /// same object.
  10686. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10687. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10688. /// A tree of sequenced regions within an expression. Two regions are
  10689. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10690. /// finish processing an expression with sequencing, such as a comma
  10691. /// expression, we fold its tree nodes into its parent, since they are
  10692. /// unsequenced with respect to nodes we will visit later.
  10693. class SequenceTree {
  10694. struct Value {
  10695. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10696. unsigned Parent : 31;
  10697. unsigned Merged : 1;
  10698. };
  10699. SmallVector<Value, 8> Values;
  10700. public:
  10701. /// A region within an expression which may be sequenced with respect
  10702. /// to some other region.
  10703. class Seq {
  10704. friend class SequenceTree;
  10705. unsigned Index;
  10706. explicit Seq(unsigned N) : Index(N) {}
  10707. public:
  10708. Seq() : Index(0) {}
  10709. };
  10710. SequenceTree() { Values.push_back(Value(0)); }
  10711. Seq root() const { return Seq(0); }
  10712. /// Create a new sequence of operations, which is an unsequenced
  10713. /// subset of \p Parent. This sequence of operations is sequenced with
  10714. /// respect to other children of \p Parent.
  10715. Seq allocate(Seq Parent) {
  10716. Values.push_back(Value(Parent.Index));
  10717. return Seq(Values.size() - 1);
  10718. }
  10719. /// Merge a sequence of operations into its parent.
  10720. void merge(Seq S) {
  10721. Values[S.Index].Merged = true;
  10722. }
  10723. /// Determine whether two operations are unsequenced. This operation
  10724. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10725. /// should have been merged into its parent as appropriate.
  10726. bool isUnsequenced(Seq Cur, Seq Old) {
  10727. unsigned C = representative(Cur.Index);
  10728. unsigned Target = representative(Old.Index);
  10729. while (C >= Target) {
  10730. if (C == Target)
  10731. return true;
  10732. C = Values[C].Parent;
  10733. }
  10734. return false;
  10735. }
  10736. private:
  10737. /// Pick a representative for a sequence.
  10738. unsigned representative(unsigned K) {
  10739. if (Values[K].Merged)
  10740. // Perform path compression as we go.
  10741. return Values[K].Parent = representative(Values[K].Parent);
  10742. return K;
  10743. }
  10744. };
  10745. /// An object for which we can track unsequenced uses.
  10746. using Object = NamedDecl *;
  10747. /// Different flavors of object usage which we track. We only track the
  10748. /// least-sequenced usage of each kind.
  10749. enum UsageKind {
  10750. /// A read of an object. Multiple unsequenced reads are OK.
  10751. UK_Use,
  10752. /// A modification of an object which is sequenced before the value
  10753. /// computation of the expression, such as ++n in C++.
  10754. UK_ModAsValue,
  10755. /// A modification of an object which is not sequenced before the value
  10756. /// computation of the expression, such as n++.
  10757. UK_ModAsSideEffect,
  10758. UK_Count = UK_ModAsSideEffect + 1
  10759. };
  10760. struct Usage {
  10761. Expr *Use;
  10762. SequenceTree::Seq Seq;
  10763. Usage() : Use(nullptr), Seq() {}
  10764. };
  10765. struct UsageInfo {
  10766. Usage Uses[UK_Count];
  10767. /// Have we issued a diagnostic for this variable already?
  10768. bool Diagnosed;
  10769. UsageInfo() : Uses(), Diagnosed(false) {}
  10770. };
  10771. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10772. Sema &SemaRef;
  10773. /// Sequenced regions within the expression.
  10774. SequenceTree Tree;
  10775. /// Declaration modifications and references which we have seen.
  10776. UsageInfoMap UsageMap;
  10777. /// The region we are currently within.
  10778. SequenceTree::Seq Region;
  10779. /// Filled in with declarations which were modified as a side-effect
  10780. /// (that is, post-increment operations).
  10781. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10782. /// Expressions to check later. We defer checking these to reduce
  10783. /// stack usage.
  10784. SmallVectorImpl<Expr *> &WorkList;
  10785. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10786. /// expression. At the end of this process, the side-effects of the evaluation
  10787. /// become sequenced with respect to the value computation of the result, so
  10788. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10789. /// UK_ModAsValue.
  10790. struct SequencedSubexpression {
  10791. SequencedSubexpression(SequenceChecker &Self)
  10792. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10793. Self.ModAsSideEffect = &ModAsSideEffect;
  10794. }
  10795. ~SequencedSubexpression() {
  10796. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10797. UsageInfo &U = Self.UsageMap[M.first];
  10798. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10799. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10800. SideEffectUsage = M.second;
  10801. }
  10802. Self.ModAsSideEffect = OldModAsSideEffect;
  10803. }
  10804. SequenceChecker &Self;
  10805. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10806. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10807. };
  10808. /// RAII object wrapping the visitation of a subexpression which we might
  10809. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10810. /// found to be non-constant, this allows us to suppress the evaluation of
  10811. /// the outer expression.
  10812. class EvaluationTracker {
  10813. public:
  10814. EvaluationTracker(SequenceChecker &Self)
  10815. : Self(Self), Prev(Self.EvalTracker) {
  10816. Self.EvalTracker = this;
  10817. }
  10818. ~EvaluationTracker() {
  10819. Self.EvalTracker = Prev;
  10820. if (Prev)
  10821. Prev->EvalOK &= EvalOK;
  10822. }
  10823. bool evaluate(const Expr *E, bool &Result) {
  10824. if (!EvalOK || E->isValueDependent())
  10825. return false;
  10826. EvalOK = E->EvaluateAsBooleanCondition(
  10827. Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
  10828. return EvalOK;
  10829. }
  10830. private:
  10831. SequenceChecker &Self;
  10832. EvaluationTracker *Prev;
  10833. bool EvalOK = true;
  10834. } *EvalTracker = nullptr;
  10835. /// Find the object which is produced by the specified expression,
  10836. /// if any.
  10837. Object getObject(Expr *E, bool Mod) const {
  10838. E = E->IgnoreParenCasts();
  10839. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10840. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10841. return getObject(UO->getSubExpr(), Mod);
  10842. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10843. if (BO->getOpcode() == BO_Comma)
  10844. return getObject(BO->getRHS(), Mod);
  10845. if (Mod && BO->isAssignmentOp())
  10846. return getObject(BO->getLHS(), Mod);
  10847. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10848. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10849. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10850. return ME->getMemberDecl();
  10851. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10852. // FIXME: If this is a reference, map through to its value.
  10853. return DRE->getDecl();
  10854. return nullptr;
  10855. }
  10856. /// Note that an object was modified or used by an expression.
  10857. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10858. Usage &U = UI.Uses[UK];
  10859. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10860. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10861. ModAsSideEffect->push_back(std::make_pair(O, U));
  10862. U.Use = Ref;
  10863. U.Seq = Region;
  10864. }
  10865. }
  10866. /// Check whether a modification or use conflicts with a prior usage.
  10867. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10868. bool IsModMod) {
  10869. if (UI.Diagnosed)
  10870. return;
  10871. const Usage &U = UI.Uses[OtherKind];
  10872. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10873. return;
  10874. Expr *Mod = U.Use;
  10875. Expr *ModOrUse = Ref;
  10876. if (OtherKind == UK_Use)
  10877. std::swap(Mod, ModOrUse);
  10878. SemaRef.DiagRuntimeBehavior(
  10879. Mod->getExprLoc(), {Mod, ModOrUse},
  10880. SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
  10881. : diag::warn_unsequenced_mod_use)
  10882. << O << SourceRange(ModOrUse->getExprLoc()));
  10883. UI.Diagnosed = true;
  10884. }
  10885. void notePreUse(Object O, Expr *Use) {
  10886. UsageInfo &U = UsageMap[O];
  10887. // Uses conflict with other modifications.
  10888. checkUsage(O, U, Use, UK_ModAsValue, false);
  10889. }
  10890. void notePostUse(Object O, Expr *Use) {
  10891. UsageInfo &U = UsageMap[O];
  10892. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10893. addUsage(U, O, Use, UK_Use);
  10894. }
  10895. void notePreMod(Object O, Expr *Mod) {
  10896. UsageInfo &U = UsageMap[O];
  10897. // Modifications conflict with other modifications and with uses.
  10898. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10899. checkUsage(O, U, Mod, UK_Use, false);
  10900. }
  10901. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10902. UsageInfo &U = UsageMap[O];
  10903. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10904. addUsage(U, O, Use, UK);
  10905. }
  10906. public:
  10907. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10908. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10909. Visit(E);
  10910. }
  10911. void VisitStmt(Stmt *S) {
  10912. // Skip all statements which aren't expressions for now.
  10913. }
  10914. void VisitExpr(Expr *E) {
  10915. // By default, just recurse to evaluated subexpressions.
  10916. Base::VisitStmt(E);
  10917. }
  10918. void VisitCastExpr(CastExpr *E) {
  10919. Object O = Object();
  10920. if (E->getCastKind() == CK_LValueToRValue)
  10921. O = getObject(E->getSubExpr(), false);
  10922. if (O)
  10923. notePreUse(O, E);
  10924. VisitExpr(E);
  10925. if (O)
  10926. notePostUse(O, E);
  10927. }
  10928. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  10929. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  10930. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  10931. SequenceTree::Seq OldRegion = Region;
  10932. {
  10933. SequencedSubexpression SeqBefore(*this);
  10934. Region = BeforeRegion;
  10935. Visit(SequencedBefore);
  10936. }
  10937. Region = AfterRegion;
  10938. Visit(SequencedAfter);
  10939. Region = OldRegion;
  10940. Tree.merge(BeforeRegion);
  10941. Tree.merge(AfterRegion);
  10942. }
  10943. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  10944. // C++17 [expr.sub]p1:
  10945. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  10946. // expression E1 is sequenced before the expression E2.
  10947. if (SemaRef.getLangOpts().CPlusPlus17)
  10948. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  10949. else
  10950. Base::VisitStmt(ASE);
  10951. }
  10952. void VisitBinComma(BinaryOperator *BO) {
  10953. // C++11 [expr.comma]p1:
  10954. // Every value computation and side effect associated with the left
  10955. // expression is sequenced before every value computation and side
  10956. // effect associated with the right expression.
  10957. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  10958. }
  10959. void VisitBinAssign(BinaryOperator *BO) {
  10960. // The modification is sequenced after the value computation of the LHS
  10961. // and RHS, so check it before inspecting the operands and update the
  10962. // map afterwards.
  10963. Object O = getObject(BO->getLHS(), true);
  10964. if (!O)
  10965. return VisitExpr(BO);
  10966. notePreMod(O, BO);
  10967. // C++11 [expr.ass]p7:
  10968. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10969. // only once.
  10970. //
  10971. // Therefore, for a compound assignment operator, O is considered used
  10972. // everywhere except within the evaluation of E1 itself.
  10973. if (isa<CompoundAssignOperator>(BO))
  10974. notePreUse(O, BO);
  10975. Visit(BO->getLHS());
  10976. if (isa<CompoundAssignOperator>(BO))
  10977. notePostUse(O, BO);
  10978. Visit(BO->getRHS());
  10979. // C++11 [expr.ass]p1:
  10980. // the assignment is sequenced [...] before the value computation of the
  10981. // assignment expression.
  10982. // C11 6.5.16/3 has no such rule.
  10983. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10984. : UK_ModAsSideEffect);
  10985. }
  10986. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10987. VisitBinAssign(CAO);
  10988. }
  10989. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10990. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10991. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10992. Object O = getObject(UO->getSubExpr(), true);
  10993. if (!O)
  10994. return VisitExpr(UO);
  10995. notePreMod(O, UO);
  10996. Visit(UO->getSubExpr());
  10997. // C++11 [expr.pre.incr]p1:
  10998. // the expression ++x is equivalent to x+=1
  10999. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  11000. : UK_ModAsSideEffect);
  11001. }
  11002. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11003. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  11004. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  11005. Object O = getObject(UO->getSubExpr(), true);
  11006. if (!O)
  11007. return VisitExpr(UO);
  11008. notePreMod(O, UO);
  11009. Visit(UO->getSubExpr());
  11010. notePostMod(O, UO, UK_ModAsSideEffect);
  11011. }
  11012. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  11013. void VisitBinLOr(BinaryOperator *BO) {
  11014. // The side-effects of the LHS of an '&&' are sequenced before the
  11015. // value computation of the RHS, and hence before the value computation
  11016. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  11017. // as if they were unconditionally sequenced.
  11018. EvaluationTracker Eval(*this);
  11019. {
  11020. SequencedSubexpression Sequenced(*this);
  11021. Visit(BO->getLHS());
  11022. }
  11023. bool Result;
  11024. if (Eval.evaluate(BO->getLHS(), Result)) {
  11025. if (!Result)
  11026. Visit(BO->getRHS());
  11027. } else {
  11028. // Check for unsequenced operations in the RHS, treating it as an
  11029. // entirely separate evaluation.
  11030. //
  11031. // FIXME: If there are operations in the RHS which are unsequenced
  11032. // with respect to operations outside the RHS, and those operations
  11033. // are unconditionally evaluated, diagnose them.
  11034. WorkList.push_back(BO->getRHS());
  11035. }
  11036. }
  11037. void VisitBinLAnd(BinaryOperator *BO) {
  11038. EvaluationTracker Eval(*this);
  11039. {
  11040. SequencedSubexpression Sequenced(*this);
  11041. Visit(BO->getLHS());
  11042. }
  11043. bool Result;
  11044. if (Eval.evaluate(BO->getLHS(), Result)) {
  11045. if (Result)
  11046. Visit(BO->getRHS());
  11047. } else {
  11048. WorkList.push_back(BO->getRHS());
  11049. }
  11050. }
  11051. // Only visit the condition, unless we can be sure which subexpression will
  11052. // be chosen.
  11053. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  11054. EvaluationTracker Eval(*this);
  11055. {
  11056. SequencedSubexpression Sequenced(*this);
  11057. Visit(CO->getCond());
  11058. }
  11059. bool Result;
  11060. if (Eval.evaluate(CO->getCond(), Result))
  11061. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  11062. else {
  11063. WorkList.push_back(CO->getTrueExpr());
  11064. WorkList.push_back(CO->getFalseExpr());
  11065. }
  11066. }
  11067. void VisitCallExpr(CallExpr *CE) {
  11068. // C++11 [intro.execution]p15:
  11069. // When calling a function [...], every value computation and side effect
  11070. // associated with any argument expression, or with the postfix expression
  11071. // designating the called function, is sequenced before execution of every
  11072. // expression or statement in the body of the function [and thus before
  11073. // the value computation of its result].
  11074. SequencedSubexpression Sequenced(*this);
  11075. Base::VisitCallExpr(CE);
  11076. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  11077. }
  11078. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  11079. // This is a call, so all subexpressions are sequenced before the result.
  11080. SequencedSubexpression Sequenced(*this);
  11081. if (!CCE->isListInitialization())
  11082. return VisitExpr(CCE);
  11083. // In C++11, list initializations are sequenced.
  11084. SmallVector<SequenceTree::Seq, 32> Elts;
  11085. SequenceTree::Seq Parent = Region;
  11086. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  11087. E = CCE->arg_end();
  11088. I != E; ++I) {
  11089. Region = Tree.allocate(Parent);
  11090. Elts.push_back(Region);
  11091. Visit(*I);
  11092. }
  11093. // Forget that the initializers are sequenced.
  11094. Region = Parent;
  11095. for (unsigned I = 0; I < Elts.size(); ++I)
  11096. Tree.merge(Elts[I]);
  11097. }
  11098. void VisitInitListExpr(InitListExpr *ILE) {
  11099. if (!SemaRef.getLangOpts().CPlusPlus11)
  11100. return VisitExpr(ILE);
  11101. // In C++11, list initializations are sequenced.
  11102. SmallVector<SequenceTree::Seq, 32> Elts;
  11103. SequenceTree::Seq Parent = Region;
  11104. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  11105. Expr *E = ILE->getInit(I);
  11106. if (!E) continue;
  11107. Region = Tree.allocate(Parent);
  11108. Elts.push_back(Region);
  11109. Visit(E);
  11110. }
  11111. // Forget that the initializers are sequenced.
  11112. Region = Parent;
  11113. for (unsigned I = 0; I < Elts.size(); ++I)
  11114. Tree.merge(Elts[I]);
  11115. }
  11116. };
  11117. } // namespace
  11118. void Sema::CheckUnsequencedOperations(Expr *E) {
  11119. SmallVector<Expr *, 8> WorkList;
  11120. WorkList.push_back(E);
  11121. while (!WorkList.empty()) {
  11122. Expr *Item = WorkList.pop_back_val();
  11123. SequenceChecker(*this, Item, WorkList);
  11124. }
  11125. }
  11126. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  11127. bool IsConstexpr) {
  11128. llvm::SaveAndRestore<bool> ConstantContext(
  11129. isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
  11130. CheckImplicitConversions(E, CheckLoc);
  11131. if (!E->isInstantiationDependent())
  11132. CheckUnsequencedOperations(E);
  11133. if (!IsConstexpr && !E->isValueDependent())
  11134. CheckForIntOverflow(E);
  11135. DiagnoseMisalignedMembers();
  11136. }
  11137. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  11138. FieldDecl *BitField,
  11139. Expr *Init) {
  11140. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  11141. }
  11142. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  11143. SourceLocation Loc) {
  11144. if (!PType->isVariablyModifiedType())
  11145. return;
  11146. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  11147. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  11148. return;
  11149. }
  11150. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  11151. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  11152. return;
  11153. }
  11154. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  11155. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  11156. return;
  11157. }
  11158. const ArrayType *AT = S.Context.getAsArrayType(PType);
  11159. if (!AT)
  11160. return;
  11161. if (AT->getSizeModifier() != ArrayType::Star) {
  11162. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  11163. return;
  11164. }
  11165. S.Diag(Loc, diag::err_array_star_in_function_definition);
  11166. }
  11167. /// CheckParmsForFunctionDef - Check that the parameters of the given
  11168. /// function are appropriate for the definition of a function. This
  11169. /// takes care of any checks that cannot be performed on the
  11170. /// declaration itself, e.g., that the types of each of the function
  11171. /// parameters are complete.
  11172. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  11173. bool CheckParameterNames) {
  11174. bool HasInvalidParm = false;
  11175. for (ParmVarDecl *Param : Parameters) {
  11176. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  11177. // function declarator that is part of a function definition of
  11178. // that function shall not have incomplete type.
  11179. //
  11180. // This is also C++ [dcl.fct]p6.
  11181. if (!Param->isInvalidDecl() &&
  11182. RequireCompleteType(Param->getLocation(), Param->getType(),
  11183. diag::err_typecheck_decl_incomplete_type)) {
  11184. Param->setInvalidDecl();
  11185. HasInvalidParm = true;
  11186. }
  11187. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  11188. // declaration of each parameter shall include an identifier.
  11189. if (CheckParameterNames &&
  11190. Param->getIdentifier() == nullptr &&
  11191. !Param->isImplicit() &&
  11192. !getLangOpts().CPlusPlus)
  11193. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11194. // C99 6.7.5.3p12:
  11195. // If the function declarator is not part of a definition of that
  11196. // function, parameters may have incomplete type and may use the [*]
  11197. // notation in their sequences of declarator specifiers to specify
  11198. // variable length array types.
  11199. QualType PType = Param->getOriginalType();
  11200. // FIXME: This diagnostic should point the '[*]' if source-location
  11201. // information is added for it.
  11202. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  11203. // If the parameter is a c++ class type and it has to be destructed in the
  11204. // callee function, declare the destructor so that it can be called by the
  11205. // callee function. Do not perform any direct access check on the dtor here.
  11206. if (!Param->isInvalidDecl()) {
  11207. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  11208. if (!ClassDecl->isInvalidDecl() &&
  11209. !ClassDecl->hasIrrelevantDestructor() &&
  11210. !ClassDecl->isDependentContext() &&
  11211. ClassDecl->isParamDestroyedInCallee()) {
  11212. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  11213. MarkFunctionReferenced(Param->getLocation(), Destructor);
  11214. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  11215. }
  11216. }
  11217. }
  11218. // Parameters with the pass_object_size attribute only need to be marked
  11219. // constant at function definitions. Because we lack information about
  11220. // whether we're on a declaration or definition when we're instantiating the
  11221. // attribute, we need to check for constness here.
  11222. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  11223. if (!Param->getType().isConstQualified())
  11224. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  11225. << Attr->getSpelling() << 1;
  11226. // Check for parameter names shadowing fields from the class.
  11227. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  11228. // The owning context for the parameter should be the function, but we
  11229. // want to see if this function's declaration context is a record.
  11230. DeclContext *DC = Param->getDeclContext();
  11231. if (DC && DC->isFunctionOrMethod()) {
  11232. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  11233. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  11234. RD, /*DeclIsField*/ false);
  11235. }
  11236. }
  11237. }
  11238. return HasInvalidParm;
  11239. }
  11240. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  11241. /// or MemberExpr.
  11242. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  11243. ASTContext &Context) {
  11244. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  11245. return Context.getDeclAlign(DRE->getDecl());
  11246. if (const auto *ME = dyn_cast<MemberExpr>(E))
  11247. return Context.getDeclAlign(ME->getMemberDecl());
  11248. return TypeAlign;
  11249. }
  11250. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  11251. /// pointer cast increases the alignment requirements.
  11252. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  11253. // This is actually a lot of work to potentially be doing on every
  11254. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  11255. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  11256. return;
  11257. // Ignore dependent types.
  11258. if (T->isDependentType() || Op->getType()->isDependentType())
  11259. return;
  11260. // Require that the destination be a pointer type.
  11261. const PointerType *DestPtr = T->getAs<PointerType>();
  11262. if (!DestPtr) return;
  11263. // If the destination has alignment 1, we're done.
  11264. QualType DestPointee = DestPtr->getPointeeType();
  11265. if (DestPointee->isIncompleteType()) return;
  11266. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  11267. if (DestAlign.isOne()) return;
  11268. // Require that the source be a pointer type.
  11269. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  11270. if (!SrcPtr) return;
  11271. QualType SrcPointee = SrcPtr->getPointeeType();
  11272. // Whitelist casts from cv void*. We already implicitly
  11273. // whitelisted casts to cv void*, since they have alignment 1.
  11274. // Also whitelist casts involving incomplete types, which implicitly
  11275. // includes 'void'.
  11276. if (SrcPointee->isIncompleteType()) return;
  11277. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  11278. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  11279. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  11280. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  11281. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  11282. if (UO->getOpcode() == UO_AddrOf)
  11283. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  11284. }
  11285. if (SrcAlign >= DestAlign) return;
  11286. Diag(TRange.getBegin(), diag::warn_cast_align)
  11287. << Op->getType() << T
  11288. << static_cast<unsigned>(SrcAlign.getQuantity())
  11289. << static_cast<unsigned>(DestAlign.getQuantity())
  11290. << TRange << Op->getSourceRange();
  11291. }
  11292. /// Check whether this array fits the idiom of a size-one tail padded
  11293. /// array member of a struct.
  11294. ///
  11295. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  11296. /// commonly used to emulate flexible arrays in C89 code.
  11297. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  11298. const NamedDecl *ND) {
  11299. if (Size != 1 || !ND) return false;
  11300. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  11301. if (!FD) return false;
  11302. // Don't consider sizes resulting from macro expansions or template argument
  11303. // substitution to form C89 tail-padded arrays.
  11304. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  11305. while (TInfo) {
  11306. TypeLoc TL = TInfo->getTypeLoc();
  11307. // Look through typedefs.
  11308. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  11309. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  11310. TInfo = TDL->getTypeSourceInfo();
  11311. continue;
  11312. }
  11313. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  11314. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  11315. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  11316. return false;
  11317. }
  11318. break;
  11319. }
  11320. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  11321. if (!RD) return false;
  11322. if (RD->isUnion()) return false;
  11323. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11324. if (!CRD->isStandardLayout()) return false;
  11325. }
  11326. // See if this is the last field decl in the record.
  11327. const Decl *D = FD;
  11328. while ((D = D->getNextDeclInContext()))
  11329. if (isa<FieldDecl>(D))
  11330. return false;
  11331. return true;
  11332. }
  11333. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11334. const ArraySubscriptExpr *ASE,
  11335. bool AllowOnePastEnd, bool IndexNegated) {
  11336. // Already diagnosed by the constant evaluator.
  11337. if (isConstantEvaluated())
  11338. return;
  11339. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11340. if (IndexExpr->isValueDependent())
  11341. return;
  11342. const Type *EffectiveType =
  11343. BaseExpr->getType()->getPointeeOrArrayElementType();
  11344. BaseExpr = BaseExpr->IgnoreParenCasts();
  11345. const ConstantArrayType *ArrayTy =
  11346. Context.getAsConstantArrayType(BaseExpr->getType());
  11347. if (!ArrayTy)
  11348. return;
  11349. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11350. if (EffectiveType->isDependentType() || BaseType->isDependentType())
  11351. return;
  11352. Expr::EvalResult Result;
  11353. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11354. return;
  11355. llvm::APSInt index = Result.Val.getInt();
  11356. if (IndexNegated)
  11357. index = -index;
  11358. const NamedDecl *ND = nullptr;
  11359. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11360. ND = DRE->getDecl();
  11361. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11362. ND = ME->getMemberDecl();
  11363. if (index.isUnsigned() || !index.isNegative()) {
  11364. // It is possible that the type of the base expression after
  11365. // IgnoreParenCasts is incomplete, even though the type of the base
  11366. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11367. // example). In this case we have no information about whether the array
  11368. // access exceeds the array bounds. However we can still diagnose an array
  11369. // access which precedes the array bounds.
  11370. if (BaseType->isIncompleteType())
  11371. return;
  11372. llvm::APInt size = ArrayTy->getSize();
  11373. if (!size.isStrictlyPositive())
  11374. return;
  11375. if (BaseType != EffectiveType) {
  11376. // Make sure we're comparing apples to apples when comparing index to size
  11377. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11378. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11379. // Handle ptrarith_typesize being zero, such as when casting to void*
  11380. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11381. if (ptrarith_typesize != array_typesize) {
  11382. // There's a cast to a different size type involved
  11383. uint64_t ratio = array_typesize / ptrarith_typesize;
  11384. // TODO: Be smarter about handling cases where array_typesize is not a
  11385. // multiple of ptrarith_typesize
  11386. if (ptrarith_typesize * ratio == array_typesize)
  11387. size *= llvm::APInt(size.getBitWidth(), ratio);
  11388. }
  11389. }
  11390. if (size.getBitWidth() > index.getBitWidth())
  11391. index = index.zext(size.getBitWidth());
  11392. else if (size.getBitWidth() < index.getBitWidth())
  11393. size = size.zext(index.getBitWidth());
  11394. // For array subscripting the index must be less than size, but for pointer
  11395. // arithmetic also allow the index (offset) to be equal to size since
  11396. // computing the next address after the end of the array is legal and
  11397. // commonly done e.g. in C++ iterators and range-based for loops.
  11398. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11399. return;
  11400. // Also don't warn for arrays of size 1 which are members of some
  11401. // structure. These are often used to approximate flexible arrays in C89
  11402. // code.
  11403. if (IsTailPaddedMemberArray(*this, size, ND))
  11404. return;
  11405. // Suppress the warning if the subscript expression (as identified by the
  11406. // ']' location) and the index expression are both from macro expansions
  11407. // within a system header.
  11408. if (ASE) {
  11409. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11410. ASE->getRBracketLoc());
  11411. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11412. SourceLocation IndexLoc =
  11413. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11414. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11415. return;
  11416. }
  11417. }
  11418. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11419. if (ASE)
  11420. DiagID = diag::warn_array_index_exceeds_bounds;
  11421. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11422. PDiag(DiagID) << index.toString(10, true)
  11423. << size.toString(10, true)
  11424. << (unsigned)size.getLimitedValue(~0U)
  11425. << IndexExpr->getSourceRange());
  11426. } else {
  11427. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11428. if (!ASE) {
  11429. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11430. if (index.isNegative()) index = -index;
  11431. }
  11432. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11433. PDiag(DiagID) << index.toString(10, true)
  11434. << IndexExpr->getSourceRange());
  11435. }
  11436. if (!ND) {
  11437. // Try harder to find a NamedDecl to point at in the note.
  11438. while (const ArraySubscriptExpr *ASE =
  11439. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11440. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11441. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11442. ND = DRE->getDecl();
  11443. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11444. ND = ME->getMemberDecl();
  11445. }
  11446. if (ND)
  11447. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11448. PDiag(diag::note_array_index_out_of_bounds)
  11449. << ND->getDeclName());
  11450. }
  11451. void Sema::CheckArrayAccess(const Expr *expr) {
  11452. int AllowOnePastEnd = 0;
  11453. while (expr) {
  11454. expr = expr->IgnoreParenImpCasts();
  11455. switch (expr->getStmtClass()) {
  11456. case Stmt::ArraySubscriptExprClass: {
  11457. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11458. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11459. AllowOnePastEnd > 0);
  11460. expr = ASE->getBase();
  11461. break;
  11462. }
  11463. case Stmt::MemberExprClass: {
  11464. expr = cast<MemberExpr>(expr)->getBase();
  11465. break;
  11466. }
  11467. case Stmt::OMPArraySectionExprClass: {
  11468. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11469. if (ASE->getLowerBound())
  11470. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11471. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11472. return;
  11473. }
  11474. case Stmt::UnaryOperatorClass: {
  11475. // Only unwrap the * and & unary operators
  11476. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11477. expr = UO->getSubExpr();
  11478. switch (UO->getOpcode()) {
  11479. case UO_AddrOf:
  11480. AllowOnePastEnd++;
  11481. break;
  11482. case UO_Deref:
  11483. AllowOnePastEnd--;
  11484. break;
  11485. default:
  11486. return;
  11487. }
  11488. break;
  11489. }
  11490. case Stmt::ConditionalOperatorClass: {
  11491. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11492. if (const Expr *lhs = cond->getLHS())
  11493. CheckArrayAccess(lhs);
  11494. if (const Expr *rhs = cond->getRHS())
  11495. CheckArrayAccess(rhs);
  11496. return;
  11497. }
  11498. case Stmt::CXXOperatorCallExprClass: {
  11499. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11500. for (const auto *Arg : OCE->arguments())
  11501. CheckArrayAccess(Arg);
  11502. return;
  11503. }
  11504. default:
  11505. return;
  11506. }
  11507. }
  11508. }
  11509. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11510. namespace {
  11511. struct RetainCycleOwner {
  11512. VarDecl *Variable = nullptr;
  11513. SourceRange Range;
  11514. SourceLocation Loc;
  11515. bool Indirect = false;
  11516. RetainCycleOwner() = default;
  11517. void setLocsFrom(Expr *e) {
  11518. Loc = e->getExprLoc();
  11519. Range = e->getSourceRange();
  11520. }
  11521. };
  11522. } // namespace
  11523. /// Consider whether capturing the given variable can possibly lead to
  11524. /// a retain cycle.
  11525. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11526. // In ARC, it's captured strongly iff the variable has __strong
  11527. // lifetime. In MRR, it's captured strongly if the variable is
  11528. // __block and has an appropriate type.
  11529. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11530. return false;
  11531. owner.Variable = var;
  11532. if (ref)
  11533. owner.setLocsFrom(ref);
  11534. return true;
  11535. }
  11536. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11537. while (true) {
  11538. e = e->IgnoreParens();
  11539. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11540. switch (cast->getCastKind()) {
  11541. case CK_BitCast:
  11542. case CK_LValueBitCast:
  11543. case CK_LValueToRValue:
  11544. case CK_ARCReclaimReturnedObject:
  11545. e = cast->getSubExpr();
  11546. continue;
  11547. default:
  11548. return false;
  11549. }
  11550. }
  11551. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11552. ObjCIvarDecl *ivar = ref->getDecl();
  11553. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11554. return false;
  11555. // Try to find a retain cycle in the base.
  11556. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11557. return false;
  11558. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11559. owner.Indirect = true;
  11560. return true;
  11561. }
  11562. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11563. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11564. if (!var) return false;
  11565. return considerVariable(var, ref, owner);
  11566. }
  11567. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11568. if (member->isArrow()) return false;
  11569. // Don't count this as an indirect ownership.
  11570. e = member->getBase();
  11571. continue;
  11572. }
  11573. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11574. // Only pay attention to pseudo-objects on property references.
  11575. ObjCPropertyRefExpr *pre
  11576. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11577. ->IgnoreParens());
  11578. if (!pre) return false;
  11579. if (pre->isImplicitProperty()) return false;
  11580. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11581. if (!property->isRetaining() &&
  11582. !(property->getPropertyIvarDecl() &&
  11583. property->getPropertyIvarDecl()->getType()
  11584. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11585. return false;
  11586. owner.Indirect = true;
  11587. if (pre->isSuperReceiver()) {
  11588. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11589. if (!owner.Variable)
  11590. return false;
  11591. owner.Loc = pre->getLocation();
  11592. owner.Range = pre->getSourceRange();
  11593. return true;
  11594. }
  11595. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11596. ->getSourceExpr());
  11597. continue;
  11598. }
  11599. // Array ivars?
  11600. return false;
  11601. }
  11602. }
  11603. namespace {
  11604. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11605. ASTContext &Context;
  11606. VarDecl *Variable;
  11607. Expr *Capturer = nullptr;
  11608. bool VarWillBeReased = false;
  11609. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11610. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11611. Context(Context), Variable(variable) {}
  11612. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11613. if (ref->getDecl() == Variable && !Capturer)
  11614. Capturer = ref;
  11615. }
  11616. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11617. if (Capturer) return;
  11618. Visit(ref->getBase());
  11619. if (Capturer && ref->isFreeIvar())
  11620. Capturer = ref;
  11621. }
  11622. void VisitBlockExpr(BlockExpr *block) {
  11623. // Look inside nested blocks
  11624. if (block->getBlockDecl()->capturesVariable(Variable))
  11625. Visit(block->getBlockDecl()->getBody());
  11626. }
  11627. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11628. if (Capturer) return;
  11629. if (OVE->getSourceExpr())
  11630. Visit(OVE->getSourceExpr());
  11631. }
  11632. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11633. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11634. return;
  11635. Expr *LHS = BinOp->getLHS();
  11636. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11637. if (DRE->getDecl() != Variable)
  11638. return;
  11639. if (Expr *RHS = BinOp->getRHS()) {
  11640. RHS = RHS->IgnoreParenCasts();
  11641. llvm::APSInt Value;
  11642. VarWillBeReased =
  11643. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11644. }
  11645. }
  11646. }
  11647. };
  11648. } // namespace
  11649. /// Check whether the given argument is a block which captures a
  11650. /// variable.
  11651. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11652. assert(owner.Variable && owner.Loc.isValid());
  11653. e = e->IgnoreParenCasts();
  11654. // Look through [^{...} copy] and Block_copy(^{...}).
  11655. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11656. Selector Cmd = ME->getSelector();
  11657. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11658. e = ME->getInstanceReceiver();
  11659. if (!e)
  11660. return nullptr;
  11661. e = e->IgnoreParenCasts();
  11662. }
  11663. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11664. if (CE->getNumArgs() == 1) {
  11665. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11666. if (Fn) {
  11667. const IdentifierInfo *FnI = Fn->getIdentifier();
  11668. if (FnI && FnI->isStr("_Block_copy")) {
  11669. e = CE->getArg(0)->IgnoreParenCasts();
  11670. }
  11671. }
  11672. }
  11673. }
  11674. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11675. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11676. return nullptr;
  11677. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11678. visitor.Visit(block->getBlockDecl()->getBody());
  11679. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11680. }
  11681. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11682. RetainCycleOwner &owner) {
  11683. assert(capturer);
  11684. assert(owner.Variable && owner.Loc.isValid());
  11685. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11686. << owner.Variable << capturer->getSourceRange();
  11687. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11688. << owner.Indirect << owner.Range;
  11689. }
  11690. /// Check for a keyword selector that starts with the word 'add' or
  11691. /// 'set'.
  11692. static bool isSetterLikeSelector(Selector sel) {
  11693. if (sel.isUnarySelector()) return false;
  11694. StringRef str = sel.getNameForSlot(0);
  11695. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11696. if (str.startswith("set"))
  11697. str = str.substr(3);
  11698. else if (str.startswith("add")) {
  11699. // Specially whitelist 'addOperationWithBlock:'.
  11700. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11701. return false;
  11702. str = str.substr(3);
  11703. }
  11704. else
  11705. return false;
  11706. if (str.empty()) return true;
  11707. return !isLowercase(str.front());
  11708. }
  11709. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11710. ObjCMessageExpr *Message) {
  11711. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11712. Message->getReceiverInterface(),
  11713. NSAPI::ClassId_NSMutableArray);
  11714. if (!IsMutableArray) {
  11715. return None;
  11716. }
  11717. Selector Sel = Message->getSelector();
  11718. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11719. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11720. if (!MKOpt) {
  11721. return None;
  11722. }
  11723. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11724. switch (MK) {
  11725. case NSAPI::NSMutableArr_addObject:
  11726. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11727. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11728. return 0;
  11729. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11730. return 1;
  11731. default:
  11732. return None;
  11733. }
  11734. return None;
  11735. }
  11736. static
  11737. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11738. ObjCMessageExpr *Message) {
  11739. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11740. Message->getReceiverInterface(),
  11741. NSAPI::ClassId_NSMutableDictionary);
  11742. if (!IsMutableDictionary) {
  11743. return None;
  11744. }
  11745. Selector Sel = Message->getSelector();
  11746. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11747. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11748. if (!MKOpt) {
  11749. return None;
  11750. }
  11751. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11752. switch (MK) {
  11753. case NSAPI::NSMutableDict_setObjectForKey:
  11754. case NSAPI::NSMutableDict_setValueForKey:
  11755. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11756. return 0;
  11757. default:
  11758. return None;
  11759. }
  11760. return None;
  11761. }
  11762. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11763. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11764. Message->getReceiverInterface(),
  11765. NSAPI::ClassId_NSMutableSet);
  11766. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11767. Message->getReceiverInterface(),
  11768. NSAPI::ClassId_NSMutableOrderedSet);
  11769. if (!IsMutableSet && !IsMutableOrderedSet) {
  11770. return None;
  11771. }
  11772. Selector Sel = Message->getSelector();
  11773. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11774. if (!MKOpt) {
  11775. return None;
  11776. }
  11777. NSAPI::NSSetMethodKind MK = *MKOpt;
  11778. switch (MK) {
  11779. case NSAPI::NSMutableSet_addObject:
  11780. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11781. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11782. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11783. return 0;
  11784. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11785. return 1;
  11786. }
  11787. return None;
  11788. }
  11789. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11790. if (!Message->isInstanceMessage()) {
  11791. return;
  11792. }
  11793. Optional<int> ArgOpt;
  11794. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11795. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11796. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11797. return;
  11798. }
  11799. int ArgIndex = *ArgOpt;
  11800. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11801. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11802. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11803. }
  11804. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11805. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11806. if (ArgRE->isObjCSelfExpr()) {
  11807. Diag(Message->getSourceRange().getBegin(),
  11808. diag::warn_objc_circular_container)
  11809. << ArgRE->getDecl() << StringRef("'super'");
  11810. }
  11811. }
  11812. } else {
  11813. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11814. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11815. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11816. }
  11817. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11818. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11819. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11820. ValueDecl *Decl = ReceiverRE->getDecl();
  11821. Diag(Message->getSourceRange().getBegin(),
  11822. diag::warn_objc_circular_container)
  11823. << Decl << Decl;
  11824. if (!ArgRE->isObjCSelfExpr()) {
  11825. Diag(Decl->getLocation(),
  11826. diag::note_objc_circular_container_declared_here)
  11827. << Decl;
  11828. }
  11829. }
  11830. }
  11831. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11832. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11833. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11834. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11835. Diag(Message->getSourceRange().getBegin(),
  11836. diag::warn_objc_circular_container)
  11837. << Decl << Decl;
  11838. Diag(Decl->getLocation(),
  11839. diag::note_objc_circular_container_declared_here)
  11840. << Decl;
  11841. }
  11842. }
  11843. }
  11844. }
  11845. }
  11846. /// Check a message send to see if it's likely to cause a retain cycle.
  11847. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11848. // Only check instance methods whose selector looks like a setter.
  11849. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11850. return;
  11851. // Try to find a variable that the receiver is strongly owned by.
  11852. RetainCycleOwner owner;
  11853. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11854. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11855. return;
  11856. } else {
  11857. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11858. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11859. owner.Loc = msg->getSuperLoc();
  11860. owner.Range = msg->getSuperLoc();
  11861. }
  11862. // Check whether the receiver is captured by any of the arguments.
  11863. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11864. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11865. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11866. // noescape blocks should not be retained by the method.
  11867. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11868. continue;
  11869. return diagnoseRetainCycle(*this, capturer, owner);
  11870. }
  11871. }
  11872. }
  11873. /// Check a property assign to see if it's likely to cause a retain cycle.
  11874. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11875. RetainCycleOwner owner;
  11876. if (!findRetainCycleOwner(*this, receiver, owner))
  11877. return;
  11878. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11879. diagnoseRetainCycle(*this, capturer, owner);
  11880. }
  11881. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11882. RetainCycleOwner Owner;
  11883. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11884. return;
  11885. // Because we don't have an expression for the variable, we have to set the
  11886. // location explicitly here.
  11887. Owner.Loc = Var->getLocation();
  11888. Owner.Range = Var->getSourceRange();
  11889. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11890. diagnoseRetainCycle(*this, Capturer, Owner);
  11891. }
  11892. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11893. Expr *RHS, bool isProperty) {
  11894. // Check if RHS is an Objective-C object literal, which also can get
  11895. // immediately zapped in a weak reference. Note that we explicitly
  11896. // allow ObjCStringLiterals, since those are designed to never really die.
  11897. RHS = RHS->IgnoreParenImpCasts();
  11898. // This enum needs to match with the 'select' in
  11899. // warn_objc_arc_literal_assign (off-by-1).
  11900. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11901. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11902. return false;
  11903. S.Diag(Loc, diag::warn_arc_literal_assign)
  11904. << (unsigned) Kind
  11905. << (isProperty ? 0 : 1)
  11906. << RHS->getSourceRange();
  11907. return true;
  11908. }
  11909. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11910. Qualifiers::ObjCLifetime LT,
  11911. Expr *RHS, bool isProperty) {
  11912. // Strip off any implicit cast added to get to the one ARC-specific.
  11913. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11914. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11915. S.Diag(Loc, diag::warn_arc_retained_assign)
  11916. << (LT == Qualifiers::OCL_ExplicitNone)
  11917. << (isProperty ? 0 : 1)
  11918. << RHS->getSourceRange();
  11919. return true;
  11920. }
  11921. RHS = cast->getSubExpr();
  11922. }
  11923. if (LT == Qualifiers::OCL_Weak &&
  11924. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11925. return true;
  11926. return false;
  11927. }
  11928. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11929. QualType LHS, Expr *RHS) {
  11930. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11931. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11932. return false;
  11933. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11934. return true;
  11935. return false;
  11936. }
  11937. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11938. Expr *LHS, Expr *RHS) {
  11939. QualType LHSType;
  11940. // PropertyRef on LHS type need be directly obtained from
  11941. // its declaration as it has a PseudoType.
  11942. ObjCPropertyRefExpr *PRE
  11943. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11944. if (PRE && !PRE->isImplicitProperty()) {
  11945. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11946. if (PD)
  11947. LHSType = PD->getType();
  11948. }
  11949. if (LHSType.isNull())
  11950. LHSType = LHS->getType();
  11951. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11952. if (LT == Qualifiers::OCL_Weak) {
  11953. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11954. getCurFunction()->markSafeWeakUse(LHS);
  11955. }
  11956. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11957. return;
  11958. // FIXME. Check for other life times.
  11959. if (LT != Qualifiers::OCL_None)
  11960. return;
  11961. if (PRE) {
  11962. if (PRE->isImplicitProperty())
  11963. return;
  11964. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11965. if (!PD)
  11966. return;
  11967. unsigned Attributes = PD->getPropertyAttributes();
  11968. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11969. // when 'assign' attribute was not explicitly specified
  11970. // by user, ignore it and rely on property type itself
  11971. // for lifetime info.
  11972. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11973. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11974. LHSType->isObjCRetainableType())
  11975. return;
  11976. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11977. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11978. Diag(Loc, diag::warn_arc_retained_property_assign)
  11979. << RHS->getSourceRange();
  11980. return;
  11981. }
  11982. RHS = cast->getSubExpr();
  11983. }
  11984. }
  11985. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11986. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11987. return;
  11988. }
  11989. }
  11990. }
  11991. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11992. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11993. SourceLocation StmtLoc,
  11994. const NullStmt *Body) {
  11995. // Do not warn if the body is a macro that expands to nothing, e.g:
  11996. //
  11997. // #define CALL(x)
  11998. // if (condition)
  11999. // CALL(0);
  12000. if (Body->hasLeadingEmptyMacro())
  12001. return false;
  12002. // Get line numbers of statement and body.
  12003. bool StmtLineInvalid;
  12004. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  12005. &StmtLineInvalid);
  12006. if (StmtLineInvalid)
  12007. return false;
  12008. bool BodyLineInvalid;
  12009. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  12010. &BodyLineInvalid);
  12011. if (BodyLineInvalid)
  12012. return false;
  12013. // Warn if null statement and body are on the same line.
  12014. if (StmtLine != BodyLine)
  12015. return false;
  12016. return true;
  12017. }
  12018. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  12019. const Stmt *Body,
  12020. unsigned DiagID) {
  12021. // Since this is a syntactic check, don't emit diagnostic for template
  12022. // instantiations, this just adds noise.
  12023. if (CurrentInstantiationScope)
  12024. return;
  12025. // The body should be a null statement.
  12026. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12027. if (!NBody)
  12028. return;
  12029. // Do the usual checks.
  12030. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12031. return;
  12032. Diag(NBody->getSemiLoc(), DiagID);
  12033. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12034. }
  12035. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  12036. const Stmt *PossibleBody) {
  12037. assert(!CurrentInstantiationScope); // Ensured by caller
  12038. SourceLocation StmtLoc;
  12039. const Stmt *Body;
  12040. unsigned DiagID;
  12041. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  12042. StmtLoc = FS->getRParenLoc();
  12043. Body = FS->getBody();
  12044. DiagID = diag::warn_empty_for_body;
  12045. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  12046. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  12047. Body = WS->getBody();
  12048. DiagID = diag::warn_empty_while_body;
  12049. } else
  12050. return; // Neither `for' nor `while'.
  12051. // The body should be a null statement.
  12052. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  12053. if (!NBody)
  12054. return;
  12055. // Skip expensive checks if diagnostic is disabled.
  12056. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  12057. return;
  12058. // Do the usual checks.
  12059. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  12060. return;
  12061. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  12062. // noise level low, emit diagnostics only if for/while is followed by a
  12063. // CompoundStmt, e.g.:
  12064. // for (int i = 0; i < n; i++);
  12065. // {
  12066. // a(i);
  12067. // }
  12068. // or if for/while is followed by a statement with more indentation
  12069. // than for/while itself:
  12070. // for (int i = 0; i < n; i++);
  12071. // a(i);
  12072. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  12073. if (!ProbableTypo) {
  12074. bool BodyColInvalid;
  12075. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  12076. PossibleBody->getBeginLoc(), &BodyColInvalid);
  12077. if (BodyColInvalid)
  12078. return;
  12079. bool StmtColInvalid;
  12080. unsigned StmtCol =
  12081. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  12082. if (StmtColInvalid)
  12083. return;
  12084. if (BodyCol > StmtCol)
  12085. ProbableTypo = true;
  12086. }
  12087. if (ProbableTypo) {
  12088. Diag(NBody->getSemiLoc(), DiagID);
  12089. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  12090. }
  12091. }
  12092. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  12093. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  12094. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  12095. SourceLocation OpLoc) {
  12096. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  12097. return;
  12098. if (inTemplateInstantiation())
  12099. return;
  12100. // Strip parens and casts away.
  12101. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12102. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12103. // Check for a call expression
  12104. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  12105. if (!CE || CE->getNumArgs() != 1)
  12106. return;
  12107. // Check for a call to std::move
  12108. if (!CE->isCallToStdMove())
  12109. return;
  12110. // Get argument from std::move
  12111. RHSExpr = CE->getArg(0);
  12112. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12113. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12114. // Two DeclRefExpr's, check that the decls are the same.
  12115. if (LHSDeclRef && RHSDeclRef) {
  12116. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12117. return;
  12118. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12119. RHSDeclRef->getDecl()->getCanonicalDecl())
  12120. return;
  12121. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12122. << LHSExpr->getSourceRange()
  12123. << RHSExpr->getSourceRange();
  12124. return;
  12125. }
  12126. // Member variables require a different approach to check for self moves.
  12127. // MemberExpr's are the same if every nested MemberExpr refers to the same
  12128. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  12129. // the base Expr's are CXXThisExpr's.
  12130. const Expr *LHSBase = LHSExpr;
  12131. const Expr *RHSBase = RHSExpr;
  12132. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  12133. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  12134. if (!LHSME || !RHSME)
  12135. return;
  12136. while (LHSME && RHSME) {
  12137. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  12138. RHSME->getMemberDecl()->getCanonicalDecl())
  12139. return;
  12140. LHSBase = LHSME->getBase();
  12141. RHSBase = RHSME->getBase();
  12142. LHSME = dyn_cast<MemberExpr>(LHSBase);
  12143. RHSME = dyn_cast<MemberExpr>(RHSBase);
  12144. }
  12145. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  12146. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  12147. if (LHSDeclRef && RHSDeclRef) {
  12148. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  12149. return;
  12150. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  12151. RHSDeclRef->getDecl()->getCanonicalDecl())
  12152. return;
  12153. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12154. << LHSExpr->getSourceRange()
  12155. << RHSExpr->getSourceRange();
  12156. return;
  12157. }
  12158. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  12159. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  12160. << LHSExpr->getSourceRange()
  12161. << RHSExpr->getSourceRange();
  12162. }
  12163. //===--- Layout compatibility ----------------------------------------------//
  12164. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  12165. /// Check if two enumeration types are layout-compatible.
  12166. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  12167. // C++11 [dcl.enum] p8:
  12168. // Two enumeration types are layout-compatible if they have the same
  12169. // underlying type.
  12170. return ED1->isComplete() && ED2->isComplete() &&
  12171. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  12172. }
  12173. /// Check if two fields are layout-compatible.
  12174. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  12175. FieldDecl *Field2) {
  12176. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  12177. return false;
  12178. if (Field1->isBitField() != Field2->isBitField())
  12179. return false;
  12180. if (Field1->isBitField()) {
  12181. // Make sure that the bit-fields are the same length.
  12182. unsigned Bits1 = Field1->getBitWidthValue(C);
  12183. unsigned Bits2 = Field2->getBitWidthValue(C);
  12184. if (Bits1 != Bits2)
  12185. return false;
  12186. }
  12187. return true;
  12188. }
  12189. /// Check if two standard-layout structs are layout-compatible.
  12190. /// (C++11 [class.mem] p17)
  12191. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  12192. RecordDecl *RD2) {
  12193. // If both records are C++ classes, check that base classes match.
  12194. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  12195. // If one of records is a CXXRecordDecl we are in C++ mode,
  12196. // thus the other one is a CXXRecordDecl, too.
  12197. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  12198. // Check number of base classes.
  12199. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  12200. return false;
  12201. // Check the base classes.
  12202. for (CXXRecordDecl::base_class_const_iterator
  12203. Base1 = D1CXX->bases_begin(),
  12204. BaseEnd1 = D1CXX->bases_end(),
  12205. Base2 = D2CXX->bases_begin();
  12206. Base1 != BaseEnd1;
  12207. ++Base1, ++Base2) {
  12208. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  12209. return false;
  12210. }
  12211. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  12212. // If only RD2 is a C++ class, it should have zero base classes.
  12213. if (D2CXX->getNumBases() > 0)
  12214. return false;
  12215. }
  12216. // Check the fields.
  12217. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  12218. Field2End = RD2->field_end(),
  12219. Field1 = RD1->field_begin(),
  12220. Field1End = RD1->field_end();
  12221. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  12222. if (!isLayoutCompatible(C, *Field1, *Field2))
  12223. return false;
  12224. }
  12225. if (Field1 != Field1End || Field2 != Field2End)
  12226. return false;
  12227. return true;
  12228. }
  12229. /// Check if two standard-layout unions are layout-compatible.
  12230. /// (C++11 [class.mem] p18)
  12231. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  12232. RecordDecl *RD2) {
  12233. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  12234. for (auto *Field2 : RD2->fields())
  12235. UnmatchedFields.insert(Field2);
  12236. for (auto *Field1 : RD1->fields()) {
  12237. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  12238. I = UnmatchedFields.begin(),
  12239. E = UnmatchedFields.end();
  12240. for ( ; I != E; ++I) {
  12241. if (isLayoutCompatible(C, Field1, *I)) {
  12242. bool Result = UnmatchedFields.erase(*I);
  12243. (void) Result;
  12244. assert(Result);
  12245. break;
  12246. }
  12247. }
  12248. if (I == E)
  12249. return false;
  12250. }
  12251. return UnmatchedFields.empty();
  12252. }
  12253. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  12254. RecordDecl *RD2) {
  12255. if (RD1->isUnion() != RD2->isUnion())
  12256. return false;
  12257. if (RD1->isUnion())
  12258. return isLayoutCompatibleUnion(C, RD1, RD2);
  12259. else
  12260. return isLayoutCompatibleStruct(C, RD1, RD2);
  12261. }
  12262. /// Check if two types are layout-compatible in C++11 sense.
  12263. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  12264. if (T1.isNull() || T2.isNull())
  12265. return false;
  12266. // C++11 [basic.types] p11:
  12267. // If two types T1 and T2 are the same type, then T1 and T2 are
  12268. // layout-compatible types.
  12269. if (C.hasSameType(T1, T2))
  12270. return true;
  12271. T1 = T1.getCanonicalType().getUnqualifiedType();
  12272. T2 = T2.getCanonicalType().getUnqualifiedType();
  12273. const Type::TypeClass TC1 = T1->getTypeClass();
  12274. const Type::TypeClass TC2 = T2->getTypeClass();
  12275. if (TC1 != TC2)
  12276. return false;
  12277. if (TC1 == Type::Enum) {
  12278. return isLayoutCompatible(C,
  12279. cast<EnumType>(T1)->getDecl(),
  12280. cast<EnumType>(T2)->getDecl());
  12281. } else if (TC1 == Type::Record) {
  12282. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  12283. return false;
  12284. return isLayoutCompatible(C,
  12285. cast<RecordType>(T1)->getDecl(),
  12286. cast<RecordType>(T2)->getDecl());
  12287. }
  12288. return false;
  12289. }
  12290. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  12291. /// Given a type tag expression find the type tag itself.
  12292. ///
  12293. /// \param TypeExpr Type tag expression, as it appears in user's code.
  12294. ///
  12295. /// \param VD Declaration of an identifier that appears in a type tag.
  12296. ///
  12297. /// \param MagicValue Type tag magic value.
  12298. ///
  12299. /// \param isConstantEvaluated wether the evalaution should be performed in
  12300. /// constant context.
  12301. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  12302. const ValueDecl **VD, uint64_t *MagicValue,
  12303. bool isConstantEvaluated) {
  12304. while(true) {
  12305. if (!TypeExpr)
  12306. return false;
  12307. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  12308. switch (TypeExpr->getStmtClass()) {
  12309. case Stmt::UnaryOperatorClass: {
  12310. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  12311. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  12312. TypeExpr = UO->getSubExpr();
  12313. continue;
  12314. }
  12315. return false;
  12316. }
  12317. case Stmt::DeclRefExprClass: {
  12318. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  12319. *VD = DRE->getDecl();
  12320. return true;
  12321. }
  12322. case Stmt::IntegerLiteralClass: {
  12323. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  12324. llvm::APInt MagicValueAPInt = IL->getValue();
  12325. if (MagicValueAPInt.getActiveBits() <= 64) {
  12326. *MagicValue = MagicValueAPInt.getZExtValue();
  12327. return true;
  12328. } else
  12329. return false;
  12330. }
  12331. case Stmt::BinaryConditionalOperatorClass:
  12332. case Stmt::ConditionalOperatorClass: {
  12333. const AbstractConditionalOperator *ACO =
  12334. cast<AbstractConditionalOperator>(TypeExpr);
  12335. bool Result;
  12336. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
  12337. isConstantEvaluated)) {
  12338. if (Result)
  12339. TypeExpr = ACO->getTrueExpr();
  12340. else
  12341. TypeExpr = ACO->getFalseExpr();
  12342. continue;
  12343. }
  12344. return false;
  12345. }
  12346. case Stmt::BinaryOperatorClass: {
  12347. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12348. if (BO->getOpcode() == BO_Comma) {
  12349. TypeExpr = BO->getRHS();
  12350. continue;
  12351. }
  12352. return false;
  12353. }
  12354. default:
  12355. return false;
  12356. }
  12357. }
  12358. }
  12359. /// Retrieve the C type corresponding to type tag TypeExpr.
  12360. ///
  12361. /// \param TypeExpr Expression that specifies a type tag.
  12362. ///
  12363. /// \param MagicValues Registered magic values.
  12364. ///
  12365. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12366. /// kind.
  12367. ///
  12368. /// \param TypeInfo Information about the corresponding C type.
  12369. ///
  12370. /// \param isConstantEvaluated wether the evalaution should be performed in
  12371. /// constant context.
  12372. ///
  12373. /// \returns true if the corresponding C type was found.
  12374. static bool GetMatchingCType(
  12375. const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
  12376. const ASTContext &Ctx,
  12377. const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
  12378. *MagicValues,
  12379. bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
  12380. bool isConstantEvaluated) {
  12381. FoundWrongKind = false;
  12382. // Variable declaration that has type_tag_for_datatype attribute.
  12383. const ValueDecl *VD = nullptr;
  12384. uint64_t MagicValue;
  12385. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
  12386. return false;
  12387. if (VD) {
  12388. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12389. if (I->getArgumentKind() != ArgumentKind) {
  12390. FoundWrongKind = true;
  12391. return false;
  12392. }
  12393. TypeInfo.Type = I->getMatchingCType();
  12394. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12395. TypeInfo.MustBeNull = I->getMustBeNull();
  12396. return true;
  12397. }
  12398. return false;
  12399. }
  12400. if (!MagicValues)
  12401. return false;
  12402. llvm::DenseMap<Sema::TypeTagMagicValue,
  12403. Sema::TypeTagData>::const_iterator I =
  12404. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12405. if (I == MagicValues->end())
  12406. return false;
  12407. TypeInfo = I->second;
  12408. return true;
  12409. }
  12410. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12411. uint64_t MagicValue, QualType Type,
  12412. bool LayoutCompatible,
  12413. bool MustBeNull) {
  12414. if (!TypeTagForDatatypeMagicValues)
  12415. TypeTagForDatatypeMagicValues.reset(
  12416. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12417. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12418. (*TypeTagForDatatypeMagicValues)[Magic] =
  12419. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12420. }
  12421. static bool IsSameCharType(QualType T1, QualType T2) {
  12422. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12423. if (!BT1)
  12424. return false;
  12425. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12426. if (!BT2)
  12427. return false;
  12428. BuiltinType::Kind T1Kind = BT1->getKind();
  12429. BuiltinType::Kind T2Kind = BT2->getKind();
  12430. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12431. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12432. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12433. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12434. }
  12435. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12436. const ArrayRef<const Expr *> ExprArgs,
  12437. SourceLocation CallSiteLoc) {
  12438. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12439. bool IsPointerAttr = Attr->getIsPointer();
  12440. // Retrieve the argument representing the 'type_tag'.
  12441. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12442. if (TypeTagIdxAST >= ExprArgs.size()) {
  12443. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12444. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12445. return;
  12446. }
  12447. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12448. bool FoundWrongKind;
  12449. TypeTagData TypeInfo;
  12450. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12451. TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
  12452. TypeInfo, isConstantEvaluated())) {
  12453. if (FoundWrongKind)
  12454. Diag(TypeTagExpr->getExprLoc(),
  12455. diag::warn_type_tag_for_datatype_wrong_kind)
  12456. << TypeTagExpr->getSourceRange();
  12457. return;
  12458. }
  12459. // Retrieve the argument representing the 'arg_idx'.
  12460. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12461. if (ArgumentIdxAST >= ExprArgs.size()) {
  12462. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12463. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12464. return;
  12465. }
  12466. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12467. if (IsPointerAttr) {
  12468. // Skip implicit cast of pointer to `void *' (as a function argument).
  12469. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12470. if (ICE->getType()->isVoidPointerType() &&
  12471. ICE->getCastKind() == CK_BitCast)
  12472. ArgumentExpr = ICE->getSubExpr();
  12473. }
  12474. QualType ArgumentType = ArgumentExpr->getType();
  12475. // Passing a `void*' pointer shouldn't trigger a warning.
  12476. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12477. return;
  12478. if (TypeInfo.MustBeNull) {
  12479. // Type tag with matching void type requires a null pointer.
  12480. if (!ArgumentExpr->isNullPointerConstant(Context,
  12481. Expr::NPC_ValueDependentIsNotNull)) {
  12482. Diag(ArgumentExpr->getExprLoc(),
  12483. diag::warn_type_safety_null_pointer_required)
  12484. << ArgumentKind->getName()
  12485. << ArgumentExpr->getSourceRange()
  12486. << TypeTagExpr->getSourceRange();
  12487. }
  12488. return;
  12489. }
  12490. QualType RequiredType = TypeInfo.Type;
  12491. if (IsPointerAttr)
  12492. RequiredType = Context.getPointerType(RequiredType);
  12493. bool mismatch = false;
  12494. if (!TypeInfo.LayoutCompatible) {
  12495. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12496. // C++11 [basic.fundamental] p1:
  12497. // Plain char, signed char, and unsigned char are three distinct types.
  12498. //
  12499. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12500. // char' depending on the current char signedness mode.
  12501. if (mismatch)
  12502. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12503. RequiredType->getPointeeType())) ||
  12504. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12505. mismatch = false;
  12506. } else
  12507. if (IsPointerAttr)
  12508. mismatch = !isLayoutCompatible(Context,
  12509. ArgumentType->getPointeeType(),
  12510. RequiredType->getPointeeType());
  12511. else
  12512. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12513. if (mismatch)
  12514. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12515. << ArgumentType << ArgumentKind
  12516. << TypeInfo.LayoutCompatible << RequiredType
  12517. << ArgumentExpr->getSourceRange()
  12518. << TypeTagExpr->getSourceRange();
  12519. }
  12520. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12521. CharUnits Alignment) {
  12522. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12523. }
  12524. void Sema::DiagnoseMisalignedMembers() {
  12525. for (MisalignedMember &m : MisalignedMembers) {
  12526. const NamedDecl *ND = m.RD;
  12527. if (ND->getName().empty()) {
  12528. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12529. ND = TD;
  12530. }
  12531. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12532. << m.MD << ND << m.E->getSourceRange();
  12533. }
  12534. MisalignedMembers.clear();
  12535. }
  12536. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12537. E = E->IgnoreParens();
  12538. if (!T->isPointerType() && !T->isIntegerType())
  12539. return;
  12540. if (isa<UnaryOperator>(E) &&
  12541. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12542. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12543. if (isa<MemberExpr>(Op)) {
  12544. auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
  12545. if (MA != MisalignedMembers.end() &&
  12546. (T->isIntegerType() ||
  12547. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12548. Context.getTypeAlignInChars(
  12549. T->getPointeeType()) <= MA->Alignment))))
  12550. MisalignedMembers.erase(MA);
  12551. }
  12552. }
  12553. }
  12554. void Sema::RefersToMemberWithReducedAlignment(
  12555. Expr *E,
  12556. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12557. Action) {
  12558. const auto *ME = dyn_cast<MemberExpr>(E);
  12559. if (!ME)
  12560. return;
  12561. // No need to check expressions with an __unaligned-qualified type.
  12562. if (E->getType().getQualifiers().hasUnaligned())
  12563. return;
  12564. // For a chain of MemberExpr like "a.b.c.d" this list
  12565. // will keep FieldDecl's like [d, c, b].
  12566. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12567. const MemberExpr *TopME = nullptr;
  12568. bool AnyIsPacked = false;
  12569. do {
  12570. QualType BaseType = ME->getBase()->getType();
  12571. if (ME->isArrow())
  12572. BaseType = BaseType->getPointeeType();
  12573. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12574. if (RD->isInvalidDecl())
  12575. return;
  12576. ValueDecl *MD = ME->getMemberDecl();
  12577. auto *FD = dyn_cast<FieldDecl>(MD);
  12578. // We do not care about non-data members.
  12579. if (!FD || FD->isInvalidDecl())
  12580. return;
  12581. AnyIsPacked =
  12582. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12583. ReverseMemberChain.push_back(FD);
  12584. TopME = ME;
  12585. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12586. } while (ME);
  12587. assert(TopME && "We did not compute a topmost MemberExpr!");
  12588. // Not the scope of this diagnostic.
  12589. if (!AnyIsPacked)
  12590. return;
  12591. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12592. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12593. // TODO: The innermost base of the member expression may be too complicated.
  12594. // For now, just disregard these cases. This is left for future
  12595. // improvement.
  12596. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12597. return;
  12598. // Alignment expected by the whole expression.
  12599. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12600. // No need to do anything else with this case.
  12601. if (ExpectedAlignment.isOne())
  12602. return;
  12603. // Synthesize offset of the whole access.
  12604. CharUnits Offset;
  12605. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12606. I++) {
  12607. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12608. }
  12609. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12610. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12611. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12612. // The base expression of the innermost MemberExpr may give
  12613. // stronger guarantees than the class containing the member.
  12614. if (DRE && !TopME->isArrow()) {
  12615. const ValueDecl *VD = DRE->getDecl();
  12616. if (!VD->getType()->isReferenceType())
  12617. CompleteObjectAlignment =
  12618. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12619. }
  12620. // Check if the synthesized offset fulfills the alignment.
  12621. if (Offset % ExpectedAlignment != 0 ||
  12622. // It may fulfill the offset it but the effective alignment may still be
  12623. // lower than the expected expression alignment.
  12624. CompleteObjectAlignment < ExpectedAlignment) {
  12625. // If this happens, we want to determine a sensible culprit of this.
  12626. // Intuitively, watching the chain of member expressions from right to
  12627. // left, we start with the required alignment (as required by the field
  12628. // type) but some packed attribute in that chain has reduced the alignment.
  12629. // It may happen that another packed structure increases it again. But if
  12630. // we are here such increase has not been enough. So pointing the first
  12631. // FieldDecl that either is packed or else its RecordDecl is,
  12632. // seems reasonable.
  12633. FieldDecl *FD = nullptr;
  12634. CharUnits Alignment;
  12635. for (FieldDecl *FDI : ReverseMemberChain) {
  12636. if (FDI->hasAttr<PackedAttr>() ||
  12637. FDI->getParent()->hasAttr<PackedAttr>()) {
  12638. FD = FDI;
  12639. Alignment = std::min(
  12640. Context.getTypeAlignInChars(FD->getType()),
  12641. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12642. break;
  12643. }
  12644. }
  12645. assert(FD && "We did not find a packed FieldDecl!");
  12646. Action(E, FD->getParent(), FD, Alignment);
  12647. }
  12648. }
  12649. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12650. using namespace std::placeholders;
  12651. RefersToMemberWithReducedAlignment(
  12652. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12653. _2, _3, _4));
  12654. }