SemaChecking.cpp 543 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940
  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/raw_ostream.h"
  87. #include <algorithm>
  88. #include <cassert>
  89. #include <cstddef>
  90. #include <cstdint>
  91. #include <functional>
  92. #include <limits>
  93. #include <string>
  94. #include <tuple>
  95. #include <utility>
  96. using namespace clang;
  97. using namespace sema;
  98. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  99. unsigned ByteNo) const {
  100. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  101. Context.getTargetInfo());
  102. }
  103. /// Checks that a call expression's argument count is the desired number.
  104. /// This is useful when doing custom type-checking. Returns true on error.
  105. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  106. unsigned argCount = call->getNumArgs();
  107. if (argCount == desiredArgCount) return false;
  108. if (argCount < desiredArgCount)
  109. return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
  110. << 0 /*function call*/ << desiredArgCount << argCount
  111. << call->getSourceRange();
  112. // Highlight all the excess arguments.
  113. SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
  114. call->getArg(argCount - 1)->getEndLoc());
  115. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  116. << 0 /*function call*/ << desiredArgCount << argCount
  117. << call->getArg(1)->getSourceRange();
  118. }
  119. /// Check that the first argument to __builtin_annotation is an integer
  120. /// and the second argument is a non-wide string literal.
  121. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  122. if (checkArgCount(S, TheCall, 2))
  123. return true;
  124. // First argument should be an integer.
  125. Expr *ValArg = TheCall->getArg(0);
  126. QualType Ty = ValArg->getType();
  127. if (!Ty->isIntegerType()) {
  128. S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
  129. << ValArg->getSourceRange();
  130. return true;
  131. }
  132. // Second argument should be a constant string.
  133. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  134. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  135. if (!Literal || !Literal->isAscii()) {
  136. S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
  137. << StrArg->getSourceRange();
  138. return true;
  139. }
  140. TheCall->setType(Ty);
  141. return false;
  142. }
  143. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  144. // We need at least one argument.
  145. if (TheCall->getNumArgs() < 1) {
  146. S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  147. << 0 << 1 << TheCall->getNumArgs()
  148. << TheCall->getCallee()->getSourceRange();
  149. return true;
  150. }
  151. // All arguments should be wide string literals.
  152. for (Expr *Arg : TheCall->arguments()) {
  153. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  154. if (!Literal || !Literal->isWide()) {
  155. S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
  156. << Arg->getSourceRange();
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  163. /// result type to the corresponding pointer type.
  164. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  165. if (checkArgCount(S, TheCall, 1))
  166. return true;
  167. ExprResult Arg(TheCall->getArg(0));
  168. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
  169. if (ResultType.isNull())
  170. return true;
  171. TheCall->setArg(0, Arg.get());
  172. TheCall->setType(ResultType);
  173. return false;
  174. }
  175. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  176. if (checkArgCount(S, TheCall, 3))
  177. return true;
  178. // First two arguments should be integers.
  179. for (unsigned I = 0; I < 2; ++I) {
  180. ExprResult Arg = TheCall->getArg(I);
  181. QualType Ty = Arg.get()->getType();
  182. if (!Ty->isIntegerType()) {
  183. S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
  184. << Ty << Arg.get()->getSourceRange();
  185. return true;
  186. }
  187. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  188. S.getASTContext(), Ty, /*consume*/ false);
  189. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  190. if (Arg.isInvalid())
  191. return true;
  192. TheCall->setArg(I, Arg.get());
  193. }
  194. // Third argument should be a pointer to a non-const integer.
  195. // IRGen correctly handles volatile, restrict, and address spaces, and
  196. // the other qualifiers aren't possible.
  197. {
  198. ExprResult Arg = TheCall->getArg(2);
  199. QualType Ty = Arg.get()->getType();
  200. const auto *PtrTy = Ty->getAs<PointerType>();
  201. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  202. !PtrTy->getPointeeType().isConstQualified())) {
  203. S.Diag(Arg.get()->getBeginLoc(),
  204. diag::err_overflow_builtin_must_be_ptr_int)
  205. << Ty << Arg.get()->getSourceRange();
  206. return true;
  207. }
  208. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  209. S.getASTContext(), Ty, /*consume*/ false);
  210. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  211. if (Arg.isInvalid())
  212. return true;
  213. TheCall->setArg(2, Arg.get());
  214. }
  215. return false;
  216. }
  217. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  218. CallExpr *TheCall, unsigned SizeIdx,
  219. unsigned DstSizeIdx,
  220. StringRef LikelyMacroName) {
  221. if (TheCall->getNumArgs() <= SizeIdx ||
  222. TheCall->getNumArgs() <= DstSizeIdx)
  223. return;
  224. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  225. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  226. Expr::EvalResult SizeResult, DstSizeResult;
  227. // find out if both sizes are known at compile time
  228. if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) ||
  229. !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context))
  230. return;
  231. llvm::APSInt Size = SizeResult.Val.getInt();
  232. llvm::APSInt DstSize = DstSizeResult.Val.getInt();
  233. if (Size.ule(DstSize))
  234. return;
  235. // Confirmed overflow, so generate the diagnostic.
  236. StringRef FunctionName = FDecl->getName();
  237. SourceLocation SL = TheCall->getBeginLoc();
  238. SourceManager &SM = S.getSourceManager();
  239. // If we're in an expansion of a macro whose name corresponds to this builtin,
  240. // use the simple macro name and location.
  241. if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
  242. LikelyMacroName) {
  243. FunctionName = LikelyMacroName;
  244. SL = SM.getImmediateMacroCallerLoc(SL);
  245. }
  246. S.Diag(SL, diag::warn_memcpy_chk_overflow)
  247. << FunctionName << DstSize.toString(/*Radix=*/10)
  248. << Size.toString(/*Radix=*/10);
  249. }
  250. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  251. if (checkArgCount(S, BuiltinCall, 2))
  252. return true;
  253. SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
  254. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  255. Expr *Call = BuiltinCall->getArg(0);
  256. Expr *Chain = BuiltinCall->getArg(1);
  257. if (Call->getStmtClass() != Stmt::CallExprClass) {
  258. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  259. << Call->getSourceRange();
  260. return true;
  261. }
  262. auto CE = cast<CallExpr>(Call);
  263. if (CE->getCallee()->getType()->isBlockPointerType()) {
  264. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  265. << Call->getSourceRange();
  266. return true;
  267. }
  268. const Decl *TargetDecl = CE->getCalleeDecl();
  269. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  270. if (FD->getBuiltinID()) {
  271. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  272. << Call->getSourceRange();
  273. return true;
  274. }
  275. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  276. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  277. << Call->getSourceRange();
  278. return true;
  279. }
  280. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  281. if (ChainResult.isInvalid())
  282. return true;
  283. if (!ChainResult.get()->getType()->isPointerType()) {
  284. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  285. << Chain->getSourceRange();
  286. return true;
  287. }
  288. QualType ReturnTy = CE->getCallReturnType(S.Context);
  289. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  290. QualType BuiltinTy = S.Context.getFunctionType(
  291. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  292. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  293. Builtin =
  294. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  295. BuiltinCall->setType(CE->getType());
  296. BuiltinCall->setValueKind(CE->getValueKind());
  297. BuiltinCall->setObjectKind(CE->getObjectKind());
  298. BuiltinCall->setCallee(Builtin);
  299. BuiltinCall->setArg(1, ChainResult.get());
  300. return false;
  301. }
  302. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  303. Scope::ScopeFlags NeededScopeFlags,
  304. unsigned DiagID) {
  305. // Scopes aren't available during instantiation. Fortunately, builtin
  306. // functions cannot be template args so they cannot be formed through template
  307. // instantiation. Therefore checking once during the parse is sufficient.
  308. if (SemaRef.inTemplateInstantiation())
  309. return false;
  310. Scope *S = SemaRef.getCurScope();
  311. while (S && !S->isSEHExceptScope())
  312. S = S->getParent();
  313. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  314. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  315. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  316. << DRE->getDecl()->getIdentifier();
  317. return true;
  318. }
  319. return false;
  320. }
  321. static inline bool isBlockPointer(Expr *Arg) {
  322. return Arg->getType()->isBlockPointerType();
  323. }
  324. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  325. /// void*, which is a requirement of device side enqueue.
  326. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  327. const BlockPointerType *BPT =
  328. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  329. ArrayRef<QualType> Params =
  330. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  331. unsigned ArgCounter = 0;
  332. bool IllegalParams = false;
  333. // Iterate through the block parameters until either one is found that is not
  334. // a local void*, or the block is valid.
  335. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  336. I != E; ++I, ++ArgCounter) {
  337. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  338. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  339. LangAS::opencl_local) {
  340. // Get the location of the error. If a block literal has been passed
  341. // (BlockExpr) then we can point straight to the offending argument,
  342. // else we just point to the variable reference.
  343. SourceLocation ErrorLoc;
  344. if (isa<BlockExpr>(BlockArg)) {
  345. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  346. ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
  347. } else if (isa<DeclRefExpr>(BlockArg)) {
  348. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
  349. }
  350. S.Diag(ErrorLoc,
  351. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  352. IllegalParams = true;
  353. }
  354. }
  355. return IllegalParams;
  356. }
  357. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  358. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  359. S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
  360. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  361. return true;
  362. }
  363. return false;
  364. }
  365. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  366. if (checkArgCount(S, TheCall, 2))
  367. return true;
  368. if (checkOpenCLSubgroupExt(S, TheCall))
  369. return true;
  370. // First argument is an ndrange_t type.
  371. Expr *NDRangeArg = TheCall->getArg(0);
  372. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  373. S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  374. << TheCall->getDirectCallee() << "'ndrange_t'";
  375. return true;
  376. }
  377. Expr *BlockArg = TheCall->getArg(1);
  378. if (!isBlockPointer(BlockArg)) {
  379. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  380. << TheCall->getDirectCallee() << "block";
  381. return true;
  382. }
  383. return checkOpenCLBlockArgs(S, BlockArg);
  384. }
  385. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  386. /// get_kernel_work_group_size
  387. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  388. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  389. if (checkArgCount(S, TheCall, 1))
  390. return true;
  391. Expr *BlockArg = TheCall->getArg(0);
  392. if (!isBlockPointer(BlockArg)) {
  393. S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  394. << TheCall->getDirectCallee() << "block";
  395. return true;
  396. }
  397. return checkOpenCLBlockArgs(S, BlockArg);
  398. }
  399. /// Diagnose integer type and any valid implicit conversion to it.
  400. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  401. const QualType &IntType);
  402. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  403. unsigned Start, unsigned End) {
  404. bool IllegalParams = false;
  405. for (unsigned I = Start; I <= End; ++I)
  406. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  407. S.Context.getSizeType());
  408. return IllegalParams;
  409. }
  410. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  411. /// 'local void*' parameter of passed block.
  412. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  413. Expr *BlockArg,
  414. unsigned NumNonVarArgs) {
  415. const BlockPointerType *BPT =
  416. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  417. unsigned NumBlockParams =
  418. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  419. unsigned TotalNumArgs = TheCall->getNumArgs();
  420. // For each argument passed to the block, a corresponding uint needs to
  421. // be passed to describe the size of the local memory.
  422. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  423. S.Diag(TheCall->getBeginLoc(),
  424. diag::err_opencl_enqueue_kernel_local_size_args);
  425. return true;
  426. }
  427. // Check that the sizes of the local memory are specified by integers.
  428. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  429. TotalNumArgs - 1);
  430. }
  431. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  432. /// overload formats specified in Table 6.13.17.1.
  433. /// int enqueue_kernel(queue_t queue,
  434. /// kernel_enqueue_flags_t flags,
  435. /// const ndrange_t ndrange,
  436. /// void (^block)(void))
  437. /// int enqueue_kernel(queue_t queue,
  438. /// kernel_enqueue_flags_t flags,
  439. /// const ndrange_t ndrange,
  440. /// uint num_events_in_wait_list,
  441. /// clk_event_t *event_wait_list,
  442. /// clk_event_t *event_ret,
  443. /// void (^block)(void))
  444. /// int enqueue_kernel(queue_t queue,
  445. /// kernel_enqueue_flags_t flags,
  446. /// const ndrange_t ndrange,
  447. /// void (^block)(local void*, ...),
  448. /// uint size0, ...)
  449. /// int enqueue_kernel(queue_t queue,
  450. /// kernel_enqueue_flags_t flags,
  451. /// const ndrange_t ndrange,
  452. /// uint num_events_in_wait_list,
  453. /// clk_event_t *event_wait_list,
  454. /// clk_event_t *event_ret,
  455. /// void (^block)(local void*, ...),
  456. /// uint size0, ...)
  457. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  458. unsigned NumArgs = TheCall->getNumArgs();
  459. if (NumArgs < 4) {
  460. S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
  461. return true;
  462. }
  463. Expr *Arg0 = TheCall->getArg(0);
  464. Expr *Arg1 = TheCall->getArg(1);
  465. Expr *Arg2 = TheCall->getArg(2);
  466. Expr *Arg3 = TheCall->getArg(3);
  467. // First argument always needs to be a queue_t type.
  468. if (!Arg0->getType()->isQueueT()) {
  469. S.Diag(TheCall->getArg(0)->getBeginLoc(),
  470. diag::err_opencl_builtin_expected_type)
  471. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  472. return true;
  473. }
  474. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  475. if (!Arg1->getType()->isIntegerType()) {
  476. S.Diag(TheCall->getArg(1)->getBeginLoc(),
  477. diag::err_opencl_builtin_expected_type)
  478. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  479. return true;
  480. }
  481. // Third argument is always an ndrange_t type.
  482. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  483. S.Diag(TheCall->getArg(2)->getBeginLoc(),
  484. diag::err_opencl_builtin_expected_type)
  485. << TheCall->getDirectCallee() << "'ndrange_t'";
  486. return true;
  487. }
  488. // With four arguments, there is only one form that the function could be
  489. // called in: no events and no variable arguments.
  490. if (NumArgs == 4) {
  491. // check that the last argument is the right block type.
  492. if (!isBlockPointer(Arg3)) {
  493. S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  494. << TheCall->getDirectCallee() << "block";
  495. return true;
  496. }
  497. // we have a block type, check the prototype
  498. const BlockPointerType *BPT =
  499. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  500. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  501. S.Diag(Arg3->getBeginLoc(),
  502. diag::err_opencl_enqueue_kernel_blocks_no_args);
  503. return true;
  504. }
  505. return false;
  506. }
  507. // we can have block + varargs.
  508. if (isBlockPointer(Arg3))
  509. return (checkOpenCLBlockArgs(S, Arg3) ||
  510. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  511. // last two cases with either exactly 7 args or 7 args and varargs.
  512. if (NumArgs >= 7) {
  513. // check common block argument.
  514. Expr *Arg6 = TheCall->getArg(6);
  515. if (!isBlockPointer(Arg6)) {
  516. S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
  517. << TheCall->getDirectCallee() << "block";
  518. return true;
  519. }
  520. if (checkOpenCLBlockArgs(S, Arg6))
  521. return true;
  522. // Forth argument has to be any integer type.
  523. if (!Arg3->getType()->isIntegerType()) {
  524. S.Diag(TheCall->getArg(3)->getBeginLoc(),
  525. diag::err_opencl_builtin_expected_type)
  526. << TheCall->getDirectCallee() << "integer";
  527. return true;
  528. }
  529. // check remaining common arguments.
  530. Expr *Arg4 = TheCall->getArg(4);
  531. Expr *Arg5 = TheCall->getArg(5);
  532. // Fifth argument is always passed as a pointer to clk_event_t.
  533. if (!Arg4->isNullPointerConstant(S.Context,
  534. Expr::NPC_ValueDependentIsNotNull) &&
  535. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  536. S.Diag(TheCall->getArg(4)->getBeginLoc(),
  537. diag::err_opencl_builtin_expected_type)
  538. << TheCall->getDirectCallee()
  539. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  540. return true;
  541. }
  542. // Sixth argument is always passed as a pointer to clk_event_t.
  543. if (!Arg5->isNullPointerConstant(S.Context,
  544. Expr::NPC_ValueDependentIsNotNull) &&
  545. !(Arg5->getType()->isPointerType() &&
  546. Arg5->getType()->getPointeeType()->isClkEventT())) {
  547. S.Diag(TheCall->getArg(5)->getBeginLoc(),
  548. diag::err_opencl_builtin_expected_type)
  549. << TheCall->getDirectCallee()
  550. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  551. return true;
  552. }
  553. if (NumArgs == 7)
  554. return false;
  555. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  556. }
  557. // None of the specific case has been detected, give generic error
  558. S.Diag(TheCall->getBeginLoc(),
  559. diag::err_opencl_enqueue_kernel_incorrect_args);
  560. return true;
  561. }
  562. /// Returns OpenCL access qual.
  563. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  564. return D->getAttr<OpenCLAccessAttr>();
  565. }
  566. /// Returns true if pipe element type is different from the pointer.
  567. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  568. const Expr *Arg0 = Call->getArg(0);
  569. // First argument type should always be pipe.
  570. if (!Arg0->getType()->isPipeType()) {
  571. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  572. << Call->getDirectCallee() << Arg0->getSourceRange();
  573. return true;
  574. }
  575. OpenCLAccessAttr *AccessQual =
  576. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  577. // Validates the access qualifier is compatible with the call.
  578. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  579. // read_only and write_only, and assumed to be read_only if no qualifier is
  580. // specified.
  581. switch (Call->getDirectCallee()->getBuiltinID()) {
  582. case Builtin::BIread_pipe:
  583. case Builtin::BIreserve_read_pipe:
  584. case Builtin::BIcommit_read_pipe:
  585. case Builtin::BIwork_group_reserve_read_pipe:
  586. case Builtin::BIsub_group_reserve_read_pipe:
  587. case Builtin::BIwork_group_commit_read_pipe:
  588. case Builtin::BIsub_group_commit_read_pipe:
  589. if (!(!AccessQual || AccessQual->isReadOnly())) {
  590. S.Diag(Arg0->getBeginLoc(),
  591. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  592. << "read_only" << Arg0->getSourceRange();
  593. return true;
  594. }
  595. break;
  596. case Builtin::BIwrite_pipe:
  597. case Builtin::BIreserve_write_pipe:
  598. case Builtin::BIcommit_write_pipe:
  599. case Builtin::BIwork_group_reserve_write_pipe:
  600. case Builtin::BIsub_group_reserve_write_pipe:
  601. case Builtin::BIwork_group_commit_write_pipe:
  602. case Builtin::BIsub_group_commit_write_pipe:
  603. if (!(AccessQual && AccessQual->isWriteOnly())) {
  604. S.Diag(Arg0->getBeginLoc(),
  605. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  606. << "write_only" << Arg0->getSourceRange();
  607. return true;
  608. }
  609. break;
  610. default:
  611. break;
  612. }
  613. return false;
  614. }
  615. /// Returns true if pipe element type is different from the pointer.
  616. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  617. const Expr *Arg0 = Call->getArg(0);
  618. const Expr *ArgIdx = Call->getArg(Idx);
  619. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  620. const QualType EltTy = PipeTy->getElementType();
  621. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  622. // The Idx argument should be a pointer and the type of the pointer and
  623. // the type of pipe element should also be the same.
  624. if (!ArgTy ||
  625. !S.Context.hasSameType(
  626. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  627. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  628. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  629. << ArgIdx->getType() << ArgIdx->getSourceRange();
  630. return true;
  631. }
  632. return false;
  633. }
  634. // Performs semantic analysis for the read/write_pipe call.
  635. // \param S Reference to the semantic analyzer.
  636. // \param Call A pointer to the builtin call.
  637. // \return True if a semantic error has been found, false otherwise.
  638. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  639. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  640. // functions have two forms.
  641. switch (Call->getNumArgs()) {
  642. case 2:
  643. if (checkOpenCLPipeArg(S, Call))
  644. return true;
  645. // The call with 2 arguments should be
  646. // read/write_pipe(pipe T, T*).
  647. // Check packet type T.
  648. if (checkOpenCLPipePacketType(S, Call, 1))
  649. return true;
  650. break;
  651. case 4: {
  652. if (checkOpenCLPipeArg(S, Call))
  653. return true;
  654. // The call with 4 arguments should be
  655. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  656. // Check reserve_id_t.
  657. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  658. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  659. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  660. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  661. return true;
  662. }
  663. // Check the index.
  664. const Expr *Arg2 = Call->getArg(2);
  665. if (!Arg2->getType()->isIntegerType() &&
  666. !Arg2->getType()->isUnsignedIntegerType()) {
  667. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  668. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  669. << Arg2->getType() << Arg2->getSourceRange();
  670. return true;
  671. }
  672. // Check packet type T.
  673. if (checkOpenCLPipePacketType(S, Call, 3))
  674. return true;
  675. } break;
  676. default:
  677. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
  678. << Call->getDirectCallee() << Call->getSourceRange();
  679. return true;
  680. }
  681. return false;
  682. }
  683. // Performs a semantic analysis on the {work_group_/sub_group_
  684. // /_}reserve_{read/write}_pipe
  685. // \param S Reference to the semantic analyzer.
  686. // \param Call The call to the builtin function to be analyzed.
  687. // \return True if a semantic error was found, false otherwise.
  688. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  689. if (checkArgCount(S, Call, 2))
  690. return true;
  691. if (checkOpenCLPipeArg(S, Call))
  692. return true;
  693. // Check the reserve size.
  694. if (!Call->getArg(1)->getType()->isIntegerType() &&
  695. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  696. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  697. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  698. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  699. return true;
  700. }
  701. // Since return type of reserve_read/write_pipe built-in function is
  702. // reserve_id_t, which is not defined in the builtin def file , we used int
  703. // as return type and need to override the return type of these functions.
  704. Call->setType(S.Context.OCLReserveIDTy);
  705. return false;
  706. }
  707. // Performs a semantic analysis on {work_group_/sub_group_
  708. // /_}commit_{read/write}_pipe
  709. // \param S Reference to the semantic analyzer.
  710. // \param Call The call to the builtin function to be analyzed.
  711. // \return True if a semantic error was found, false otherwise.
  712. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  713. if (checkArgCount(S, Call, 2))
  714. return true;
  715. if (checkOpenCLPipeArg(S, Call))
  716. return true;
  717. // Check reserve_id_t.
  718. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  719. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
  720. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  721. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  722. return true;
  723. }
  724. return false;
  725. }
  726. // Performs a semantic analysis on the call to built-in Pipe
  727. // Query Functions.
  728. // \param S Reference to the semantic analyzer.
  729. // \param Call The call to the builtin function to be analyzed.
  730. // \return True if a semantic error was found, false otherwise.
  731. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  732. if (checkArgCount(S, Call, 1))
  733. return true;
  734. if (!Call->getArg(0)->getType()->isPipeType()) {
  735. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
  736. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  737. return true;
  738. }
  739. return false;
  740. }
  741. // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  742. // Performs semantic analysis for the to_global/local/private call.
  743. // \param S Reference to the semantic analyzer.
  744. // \param BuiltinID ID of the builtin function.
  745. // \param Call A pointer to the builtin call.
  746. // \return True if a semantic error has been found, false otherwise.
  747. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  748. CallExpr *Call) {
  749. if (Call->getNumArgs() != 1) {
  750. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
  751. << Call->getDirectCallee() << Call->getSourceRange();
  752. return true;
  753. }
  754. auto RT = Call->getArg(0)->getType();
  755. if (!RT->isPointerType() || RT->getPointeeType()
  756. .getAddressSpace() == LangAS::opencl_constant) {
  757. S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
  758. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  759. return true;
  760. }
  761. if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
  762. S.Diag(Call->getArg(0)->getBeginLoc(),
  763. diag::warn_opencl_generic_address_space_arg)
  764. << Call->getDirectCallee()->getNameInfo().getAsString()
  765. << Call->getArg(0)->getSourceRange();
  766. }
  767. RT = RT->getPointeeType();
  768. auto Qual = RT.getQualifiers();
  769. switch (BuiltinID) {
  770. case Builtin::BIto_global:
  771. Qual.setAddressSpace(LangAS::opencl_global);
  772. break;
  773. case Builtin::BIto_local:
  774. Qual.setAddressSpace(LangAS::opencl_local);
  775. break;
  776. case Builtin::BIto_private:
  777. Qual.setAddressSpace(LangAS::opencl_private);
  778. break;
  779. default:
  780. llvm_unreachable("Invalid builtin function");
  781. }
  782. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  783. RT.getUnqualifiedType(), Qual)));
  784. return false;
  785. }
  786. static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
  787. if (checkArgCount(S, TheCall, 1))
  788. return ExprError();
  789. // Compute __builtin_launder's parameter type from the argument.
  790. // The parameter type is:
  791. // * The type of the argument if it's not an array or function type,
  792. // Otherwise,
  793. // * The decayed argument type.
  794. QualType ParamTy = [&]() {
  795. QualType ArgTy = TheCall->getArg(0)->getType();
  796. if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
  797. return S.Context.getPointerType(Ty->getElementType());
  798. if (ArgTy->isFunctionType()) {
  799. return S.Context.getPointerType(ArgTy);
  800. }
  801. return ArgTy;
  802. }();
  803. TheCall->setType(ParamTy);
  804. auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
  805. if (!ParamTy->isPointerType())
  806. return 0;
  807. if (ParamTy->isFunctionPointerType())
  808. return 1;
  809. if (ParamTy->isVoidPointerType())
  810. return 2;
  811. return llvm::Optional<unsigned>{};
  812. }();
  813. if (DiagSelect.hasValue()) {
  814. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
  815. << DiagSelect.getValue() << TheCall->getSourceRange();
  816. return ExprError();
  817. }
  818. // We either have an incomplete class type, or we have a class template
  819. // whose instantiation has not been forced. Example:
  820. //
  821. // template <class T> struct Foo { T value; };
  822. // Foo<int> *p = nullptr;
  823. // auto *d = __builtin_launder(p);
  824. if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
  825. diag::err_incomplete_type))
  826. return ExprError();
  827. assert(ParamTy->getPointeeType()->isObjectType() &&
  828. "Unhandled non-object pointer case");
  829. InitializedEntity Entity =
  830. InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
  831. ExprResult Arg =
  832. S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
  833. if (Arg.isInvalid())
  834. return ExprError();
  835. TheCall->setArg(0, Arg.get());
  836. return TheCall;
  837. }
  838. // Emit an error and return true if the current architecture is not in the list
  839. // of supported architectures.
  840. static bool
  841. CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
  842. ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
  843. llvm::Triple::ArchType CurArch =
  844. S.getASTContext().getTargetInfo().getTriple().getArch();
  845. if (llvm::is_contained(SupportedArchs, CurArch))
  846. return false;
  847. S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
  848. << TheCall->getSourceRange();
  849. return true;
  850. }
  851. ExprResult
  852. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  853. CallExpr *TheCall) {
  854. ExprResult TheCallResult(TheCall);
  855. // Find out if any arguments are required to be integer constant expressions.
  856. unsigned ICEArguments = 0;
  857. ASTContext::GetBuiltinTypeError Error;
  858. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  859. if (Error != ASTContext::GE_None)
  860. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  861. // If any arguments are required to be ICE's, check and diagnose.
  862. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  863. // Skip arguments not required to be ICE's.
  864. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  865. llvm::APSInt Result;
  866. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  867. return true;
  868. ICEArguments &= ~(1 << ArgNo);
  869. }
  870. switch (BuiltinID) {
  871. case Builtin::BI__builtin___CFStringMakeConstantString:
  872. assert(TheCall->getNumArgs() == 1 &&
  873. "Wrong # arguments to builtin CFStringMakeConstantString");
  874. if (CheckObjCString(TheCall->getArg(0)))
  875. return ExprError();
  876. break;
  877. case Builtin::BI__builtin_ms_va_start:
  878. case Builtin::BI__builtin_stdarg_start:
  879. case Builtin::BI__builtin_va_start:
  880. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  881. return ExprError();
  882. break;
  883. case Builtin::BI__va_start: {
  884. switch (Context.getTargetInfo().getTriple().getArch()) {
  885. case llvm::Triple::aarch64:
  886. case llvm::Triple::arm:
  887. case llvm::Triple::thumb:
  888. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  889. return ExprError();
  890. break;
  891. default:
  892. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  893. return ExprError();
  894. break;
  895. }
  896. break;
  897. }
  898. // The acquire, release, and no fence variants are ARM and AArch64 only.
  899. case Builtin::BI_interlockedbittestandset_acq:
  900. case Builtin::BI_interlockedbittestandset_rel:
  901. case Builtin::BI_interlockedbittestandset_nf:
  902. case Builtin::BI_interlockedbittestandreset_acq:
  903. case Builtin::BI_interlockedbittestandreset_rel:
  904. case Builtin::BI_interlockedbittestandreset_nf:
  905. if (CheckBuiltinTargetSupport(
  906. *this, BuiltinID, TheCall,
  907. {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
  908. return ExprError();
  909. break;
  910. // The 64-bit bittest variants are x64, ARM, and AArch64 only.
  911. case Builtin::BI_bittest64:
  912. case Builtin::BI_bittestandcomplement64:
  913. case Builtin::BI_bittestandreset64:
  914. case Builtin::BI_bittestandset64:
  915. case Builtin::BI_interlockedbittestandreset64:
  916. case Builtin::BI_interlockedbittestandset64:
  917. if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
  918. {llvm::Triple::x86_64, llvm::Triple::arm,
  919. llvm::Triple::thumb, llvm::Triple::aarch64}))
  920. return ExprError();
  921. break;
  922. case Builtin::BI__builtin_isgreater:
  923. case Builtin::BI__builtin_isgreaterequal:
  924. case Builtin::BI__builtin_isless:
  925. case Builtin::BI__builtin_islessequal:
  926. case Builtin::BI__builtin_islessgreater:
  927. case Builtin::BI__builtin_isunordered:
  928. if (SemaBuiltinUnorderedCompare(TheCall))
  929. return ExprError();
  930. break;
  931. case Builtin::BI__builtin_fpclassify:
  932. if (SemaBuiltinFPClassification(TheCall, 6))
  933. return ExprError();
  934. break;
  935. case Builtin::BI__builtin_isfinite:
  936. case Builtin::BI__builtin_isinf:
  937. case Builtin::BI__builtin_isinf_sign:
  938. case Builtin::BI__builtin_isnan:
  939. case Builtin::BI__builtin_isnormal:
  940. case Builtin::BI__builtin_signbit:
  941. case Builtin::BI__builtin_signbitf:
  942. case Builtin::BI__builtin_signbitl:
  943. if (SemaBuiltinFPClassification(TheCall, 1))
  944. return ExprError();
  945. break;
  946. case Builtin::BI__builtin_shufflevector:
  947. return SemaBuiltinShuffleVector(TheCall);
  948. // TheCall will be freed by the smart pointer here, but that's fine, since
  949. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  950. case Builtin::BI__builtin_prefetch:
  951. if (SemaBuiltinPrefetch(TheCall))
  952. return ExprError();
  953. break;
  954. case Builtin::BI__builtin_alloca_with_align:
  955. if (SemaBuiltinAllocaWithAlign(TheCall))
  956. return ExprError();
  957. break;
  958. case Builtin::BI__assume:
  959. case Builtin::BI__builtin_assume:
  960. if (SemaBuiltinAssume(TheCall))
  961. return ExprError();
  962. break;
  963. case Builtin::BI__builtin_assume_aligned:
  964. if (SemaBuiltinAssumeAligned(TheCall))
  965. return ExprError();
  966. break;
  967. case Builtin::BI__builtin_object_size:
  968. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  969. return ExprError();
  970. break;
  971. case Builtin::BI__builtin_longjmp:
  972. if (SemaBuiltinLongjmp(TheCall))
  973. return ExprError();
  974. break;
  975. case Builtin::BI__builtin_setjmp:
  976. if (SemaBuiltinSetjmp(TheCall))
  977. return ExprError();
  978. break;
  979. case Builtin::BI_setjmp:
  980. case Builtin::BI_setjmpex:
  981. if (checkArgCount(*this, TheCall, 1))
  982. return true;
  983. break;
  984. case Builtin::BI__builtin_classify_type:
  985. if (checkArgCount(*this, TheCall, 1)) return true;
  986. TheCall->setType(Context.IntTy);
  987. break;
  988. case Builtin::BI__builtin_constant_p:
  989. if (checkArgCount(*this, TheCall, 1)) return true;
  990. TheCall->setType(Context.IntTy);
  991. break;
  992. case Builtin::BI__builtin_launder:
  993. return SemaBuiltinLaunder(*this, TheCall);
  994. case Builtin::BI__sync_fetch_and_add:
  995. case Builtin::BI__sync_fetch_and_add_1:
  996. case Builtin::BI__sync_fetch_and_add_2:
  997. case Builtin::BI__sync_fetch_and_add_4:
  998. case Builtin::BI__sync_fetch_and_add_8:
  999. case Builtin::BI__sync_fetch_and_add_16:
  1000. case Builtin::BI__sync_fetch_and_sub:
  1001. case Builtin::BI__sync_fetch_and_sub_1:
  1002. case Builtin::BI__sync_fetch_and_sub_2:
  1003. case Builtin::BI__sync_fetch_and_sub_4:
  1004. case Builtin::BI__sync_fetch_and_sub_8:
  1005. case Builtin::BI__sync_fetch_and_sub_16:
  1006. case Builtin::BI__sync_fetch_and_or:
  1007. case Builtin::BI__sync_fetch_and_or_1:
  1008. case Builtin::BI__sync_fetch_and_or_2:
  1009. case Builtin::BI__sync_fetch_and_or_4:
  1010. case Builtin::BI__sync_fetch_and_or_8:
  1011. case Builtin::BI__sync_fetch_and_or_16:
  1012. case Builtin::BI__sync_fetch_and_and:
  1013. case Builtin::BI__sync_fetch_and_and_1:
  1014. case Builtin::BI__sync_fetch_and_and_2:
  1015. case Builtin::BI__sync_fetch_and_and_4:
  1016. case Builtin::BI__sync_fetch_and_and_8:
  1017. case Builtin::BI__sync_fetch_and_and_16:
  1018. case Builtin::BI__sync_fetch_and_xor:
  1019. case Builtin::BI__sync_fetch_and_xor_1:
  1020. case Builtin::BI__sync_fetch_and_xor_2:
  1021. case Builtin::BI__sync_fetch_and_xor_4:
  1022. case Builtin::BI__sync_fetch_and_xor_8:
  1023. case Builtin::BI__sync_fetch_and_xor_16:
  1024. case Builtin::BI__sync_fetch_and_nand:
  1025. case Builtin::BI__sync_fetch_and_nand_1:
  1026. case Builtin::BI__sync_fetch_and_nand_2:
  1027. case Builtin::BI__sync_fetch_and_nand_4:
  1028. case Builtin::BI__sync_fetch_and_nand_8:
  1029. case Builtin::BI__sync_fetch_and_nand_16:
  1030. case Builtin::BI__sync_add_and_fetch:
  1031. case Builtin::BI__sync_add_and_fetch_1:
  1032. case Builtin::BI__sync_add_and_fetch_2:
  1033. case Builtin::BI__sync_add_and_fetch_4:
  1034. case Builtin::BI__sync_add_and_fetch_8:
  1035. case Builtin::BI__sync_add_and_fetch_16:
  1036. case Builtin::BI__sync_sub_and_fetch:
  1037. case Builtin::BI__sync_sub_and_fetch_1:
  1038. case Builtin::BI__sync_sub_and_fetch_2:
  1039. case Builtin::BI__sync_sub_and_fetch_4:
  1040. case Builtin::BI__sync_sub_and_fetch_8:
  1041. case Builtin::BI__sync_sub_and_fetch_16:
  1042. case Builtin::BI__sync_and_and_fetch:
  1043. case Builtin::BI__sync_and_and_fetch_1:
  1044. case Builtin::BI__sync_and_and_fetch_2:
  1045. case Builtin::BI__sync_and_and_fetch_4:
  1046. case Builtin::BI__sync_and_and_fetch_8:
  1047. case Builtin::BI__sync_and_and_fetch_16:
  1048. case Builtin::BI__sync_or_and_fetch:
  1049. case Builtin::BI__sync_or_and_fetch_1:
  1050. case Builtin::BI__sync_or_and_fetch_2:
  1051. case Builtin::BI__sync_or_and_fetch_4:
  1052. case Builtin::BI__sync_or_and_fetch_8:
  1053. case Builtin::BI__sync_or_and_fetch_16:
  1054. case Builtin::BI__sync_xor_and_fetch:
  1055. case Builtin::BI__sync_xor_and_fetch_1:
  1056. case Builtin::BI__sync_xor_and_fetch_2:
  1057. case Builtin::BI__sync_xor_and_fetch_4:
  1058. case Builtin::BI__sync_xor_and_fetch_8:
  1059. case Builtin::BI__sync_xor_and_fetch_16:
  1060. case Builtin::BI__sync_nand_and_fetch:
  1061. case Builtin::BI__sync_nand_and_fetch_1:
  1062. case Builtin::BI__sync_nand_and_fetch_2:
  1063. case Builtin::BI__sync_nand_and_fetch_4:
  1064. case Builtin::BI__sync_nand_and_fetch_8:
  1065. case Builtin::BI__sync_nand_and_fetch_16:
  1066. case Builtin::BI__sync_val_compare_and_swap:
  1067. case Builtin::BI__sync_val_compare_and_swap_1:
  1068. case Builtin::BI__sync_val_compare_and_swap_2:
  1069. case Builtin::BI__sync_val_compare_and_swap_4:
  1070. case Builtin::BI__sync_val_compare_and_swap_8:
  1071. case Builtin::BI__sync_val_compare_and_swap_16:
  1072. case Builtin::BI__sync_bool_compare_and_swap:
  1073. case Builtin::BI__sync_bool_compare_and_swap_1:
  1074. case Builtin::BI__sync_bool_compare_and_swap_2:
  1075. case Builtin::BI__sync_bool_compare_and_swap_4:
  1076. case Builtin::BI__sync_bool_compare_and_swap_8:
  1077. case Builtin::BI__sync_bool_compare_and_swap_16:
  1078. case Builtin::BI__sync_lock_test_and_set:
  1079. case Builtin::BI__sync_lock_test_and_set_1:
  1080. case Builtin::BI__sync_lock_test_and_set_2:
  1081. case Builtin::BI__sync_lock_test_and_set_4:
  1082. case Builtin::BI__sync_lock_test_and_set_8:
  1083. case Builtin::BI__sync_lock_test_and_set_16:
  1084. case Builtin::BI__sync_lock_release:
  1085. case Builtin::BI__sync_lock_release_1:
  1086. case Builtin::BI__sync_lock_release_2:
  1087. case Builtin::BI__sync_lock_release_4:
  1088. case Builtin::BI__sync_lock_release_8:
  1089. case Builtin::BI__sync_lock_release_16:
  1090. case Builtin::BI__sync_swap:
  1091. case Builtin::BI__sync_swap_1:
  1092. case Builtin::BI__sync_swap_2:
  1093. case Builtin::BI__sync_swap_4:
  1094. case Builtin::BI__sync_swap_8:
  1095. case Builtin::BI__sync_swap_16:
  1096. return SemaBuiltinAtomicOverloaded(TheCallResult);
  1097. case Builtin::BI__sync_synchronize:
  1098. Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
  1099. << TheCall->getCallee()->getSourceRange();
  1100. break;
  1101. case Builtin::BI__builtin_nontemporal_load:
  1102. case Builtin::BI__builtin_nontemporal_store:
  1103. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  1104. #define BUILTIN(ID, TYPE, ATTRS)
  1105. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  1106. case Builtin::BI##ID: \
  1107. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  1108. #include "clang/Basic/Builtins.def"
  1109. case Builtin::BI__annotation:
  1110. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  1111. return ExprError();
  1112. break;
  1113. case Builtin::BI__builtin_annotation:
  1114. if (SemaBuiltinAnnotation(*this, TheCall))
  1115. return ExprError();
  1116. break;
  1117. case Builtin::BI__builtin_addressof:
  1118. if (SemaBuiltinAddressof(*this, TheCall))
  1119. return ExprError();
  1120. break;
  1121. case Builtin::BI__builtin_add_overflow:
  1122. case Builtin::BI__builtin_sub_overflow:
  1123. case Builtin::BI__builtin_mul_overflow:
  1124. if (SemaBuiltinOverflow(*this, TheCall))
  1125. return ExprError();
  1126. break;
  1127. case Builtin::BI__builtin_operator_new:
  1128. case Builtin::BI__builtin_operator_delete: {
  1129. bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
  1130. ExprResult Res =
  1131. SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
  1132. if (Res.isInvalid())
  1133. CorrectDelayedTyposInExpr(TheCallResult.get());
  1134. return Res;
  1135. }
  1136. case Builtin::BI__builtin_dump_struct: {
  1137. // We first want to ensure we are called with 2 arguments
  1138. if (checkArgCount(*this, TheCall, 2))
  1139. return ExprError();
  1140. // Ensure that the first argument is of type 'struct XX *'
  1141. const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
  1142. const QualType PtrArgType = PtrArg->getType();
  1143. if (!PtrArgType->isPointerType() ||
  1144. !PtrArgType->getPointeeType()->isRecordType()) {
  1145. Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1146. << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
  1147. << "structure pointer";
  1148. return ExprError();
  1149. }
  1150. // Ensure that the second argument is of type 'FunctionType'
  1151. const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
  1152. const QualType FnPtrArgType = FnPtrArg->getType();
  1153. if (!FnPtrArgType->isPointerType()) {
  1154. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1155. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1156. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1157. return ExprError();
  1158. }
  1159. const auto *FuncType =
  1160. FnPtrArgType->getPointeeType()->getAs<FunctionType>();
  1161. if (!FuncType) {
  1162. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1163. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
  1164. << FnPtrArgType << "'int (*)(const char *, ...)'";
  1165. return ExprError();
  1166. }
  1167. if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
  1168. if (!FT->getNumParams()) {
  1169. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1170. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1171. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1172. return ExprError();
  1173. }
  1174. QualType PT = FT->getParamType(0);
  1175. if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
  1176. !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
  1177. !PT->getPointeeType().isConstQualified()) {
  1178. Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  1179. << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
  1180. << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
  1181. return ExprError();
  1182. }
  1183. }
  1184. TheCall->setType(Context.IntTy);
  1185. break;
  1186. }
  1187. // check secure string manipulation functions where overflows
  1188. // are detectable at compile time
  1189. case Builtin::BI__builtin___memcpy_chk:
  1190. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
  1191. break;
  1192. case Builtin::BI__builtin___memmove_chk:
  1193. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
  1194. break;
  1195. case Builtin::BI__builtin___memset_chk:
  1196. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
  1197. break;
  1198. case Builtin::BI__builtin___strlcat_chk:
  1199. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
  1200. break;
  1201. case Builtin::BI__builtin___strlcpy_chk:
  1202. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
  1203. break;
  1204. case Builtin::BI__builtin___strncat_chk:
  1205. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
  1206. break;
  1207. case Builtin::BI__builtin___strncpy_chk:
  1208. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
  1209. break;
  1210. case Builtin::BI__builtin___stpncpy_chk:
  1211. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
  1212. break;
  1213. case Builtin::BI__builtin___memccpy_chk:
  1214. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
  1215. break;
  1216. case Builtin::BI__builtin___snprintf_chk:
  1217. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
  1218. break;
  1219. case Builtin::BI__builtin___vsnprintf_chk:
  1220. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
  1221. break;
  1222. case Builtin::BI__builtin_call_with_static_chain:
  1223. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1224. return ExprError();
  1225. break;
  1226. case Builtin::BI__exception_code:
  1227. case Builtin::BI_exception_code:
  1228. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1229. diag::err_seh___except_block))
  1230. return ExprError();
  1231. break;
  1232. case Builtin::BI__exception_info:
  1233. case Builtin::BI_exception_info:
  1234. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1235. diag::err_seh___except_filter))
  1236. return ExprError();
  1237. break;
  1238. case Builtin::BI__GetExceptionInfo:
  1239. if (checkArgCount(*this, TheCall, 1))
  1240. return ExprError();
  1241. if (CheckCXXThrowOperand(
  1242. TheCall->getBeginLoc(),
  1243. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1244. TheCall))
  1245. return ExprError();
  1246. TheCall->setType(Context.VoidPtrTy);
  1247. break;
  1248. // OpenCL v2.0, s6.13.16 - Pipe functions
  1249. case Builtin::BIread_pipe:
  1250. case Builtin::BIwrite_pipe:
  1251. // Since those two functions are declared with var args, we need a semantic
  1252. // check for the argument.
  1253. if (SemaBuiltinRWPipe(*this, TheCall))
  1254. return ExprError();
  1255. break;
  1256. case Builtin::BIreserve_read_pipe:
  1257. case Builtin::BIreserve_write_pipe:
  1258. case Builtin::BIwork_group_reserve_read_pipe:
  1259. case Builtin::BIwork_group_reserve_write_pipe:
  1260. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1261. return ExprError();
  1262. break;
  1263. case Builtin::BIsub_group_reserve_read_pipe:
  1264. case Builtin::BIsub_group_reserve_write_pipe:
  1265. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1266. SemaBuiltinReserveRWPipe(*this, TheCall))
  1267. return ExprError();
  1268. break;
  1269. case Builtin::BIcommit_read_pipe:
  1270. case Builtin::BIcommit_write_pipe:
  1271. case Builtin::BIwork_group_commit_read_pipe:
  1272. case Builtin::BIwork_group_commit_write_pipe:
  1273. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1274. return ExprError();
  1275. break;
  1276. case Builtin::BIsub_group_commit_read_pipe:
  1277. case Builtin::BIsub_group_commit_write_pipe:
  1278. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1279. SemaBuiltinCommitRWPipe(*this, TheCall))
  1280. return ExprError();
  1281. break;
  1282. case Builtin::BIget_pipe_num_packets:
  1283. case Builtin::BIget_pipe_max_packets:
  1284. if (SemaBuiltinPipePackets(*this, TheCall))
  1285. return ExprError();
  1286. break;
  1287. case Builtin::BIto_global:
  1288. case Builtin::BIto_local:
  1289. case Builtin::BIto_private:
  1290. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1291. return ExprError();
  1292. break;
  1293. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1294. case Builtin::BIenqueue_kernel:
  1295. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1296. return ExprError();
  1297. break;
  1298. case Builtin::BIget_kernel_work_group_size:
  1299. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1300. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1301. return ExprError();
  1302. break;
  1303. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1304. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1305. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1306. return ExprError();
  1307. break;
  1308. case Builtin::BI__builtin_os_log_format:
  1309. case Builtin::BI__builtin_os_log_format_buffer_size:
  1310. if (SemaBuiltinOSLogFormat(TheCall))
  1311. return ExprError();
  1312. break;
  1313. }
  1314. // Since the target specific builtins for each arch overlap, only check those
  1315. // of the arch we are compiling for.
  1316. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1317. switch (Context.getTargetInfo().getTriple().getArch()) {
  1318. case llvm::Triple::arm:
  1319. case llvm::Triple::armeb:
  1320. case llvm::Triple::thumb:
  1321. case llvm::Triple::thumbeb:
  1322. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1323. return ExprError();
  1324. break;
  1325. case llvm::Triple::aarch64:
  1326. case llvm::Triple::aarch64_be:
  1327. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1328. return ExprError();
  1329. break;
  1330. case llvm::Triple::hexagon:
  1331. if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
  1332. return ExprError();
  1333. break;
  1334. case llvm::Triple::mips:
  1335. case llvm::Triple::mipsel:
  1336. case llvm::Triple::mips64:
  1337. case llvm::Triple::mips64el:
  1338. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1339. return ExprError();
  1340. break;
  1341. case llvm::Triple::systemz:
  1342. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1343. return ExprError();
  1344. break;
  1345. case llvm::Triple::x86:
  1346. case llvm::Triple::x86_64:
  1347. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1348. return ExprError();
  1349. break;
  1350. case llvm::Triple::ppc:
  1351. case llvm::Triple::ppc64:
  1352. case llvm::Triple::ppc64le:
  1353. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1354. return ExprError();
  1355. break;
  1356. default:
  1357. break;
  1358. }
  1359. }
  1360. return TheCallResult;
  1361. }
  1362. // Get the valid immediate range for the specified NEON type code.
  1363. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1364. NeonTypeFlags Type(t);
  1365. int IsQuad = ForceQuad ? true : Type.isQuad();
  1366. switch (Type.getEltType()) {
  1367. case NeonTypeFlags::Int8:
  1368. case NeonTypeFlags::Poly8:
  1369. return shift ? 7 : (8 << IsQuad) - 1;
  1370. case NeonTypeFlags::Int16:
  1371. case NeonTypeFlags::Poly16:
  1372. return shift ? 15 : (4 << IsQuad) - 1;
  1373. case NeonTypeFlags::Int32:
  1374. return shift ? 31 : (2 << IsQuad) - 1;
  1375. case NeonTypeFlags::Int64:
  1376. case NeonTypeFlags::Poly64:
  1377. return shift ? 63 : (1 << IsQuad) - 1;
  1378. case NeonTypeFlags::Poly128:
  1379. return shift ? 127 : (1 << IsQuad) - 1;
  1380. case NeonTypeFlags::Float16:
  1381. assert(!shift && "cannot shift float types!");
  1382. return (4 << IsQuad) - 1;
  1383. case NeonTypeFlags::Float32:
  1384. assert(!shift && "cannot shift float types!");
  1385. return (2 << IsQuad) - 1;
  1386. case NeonTypeFlags::Float64:
  1387. assert(!shift && "cannot shift float types!");
  1388. return (1 << IsQuad) - 1;
  1389. }
  1390. llvm_unreachable("Invalid NeonTypeFlag!");
  1391. }
  1392. /// getNeonEltType - Return the QualType corresponding to the elements of
  1393. /// the vector type specified by the NeonTypeFlags. This is used to check
  1394. /// the pointer arguments for Neon load/store intrinsics.
  1395. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1396. bool IsPolyUnsigned, bool IsInt64Long) {
  1397. switch (Flags.getEltType()) {
  1398. case NeonTypeFlags::Int8:
  1399. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1400. case NeonTypeFlags::Int16:
  1401. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1402. case NeonTypeFlags::Int32:
  1403. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1404. case NeonTypeFlags::Int64:
  1405. if (IsInt64Long)
  1406. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1407. else
  1408. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1409. : Context.LongLongTy;
  1410. case NeonTypeFlags::Poly8:
  1411. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1412. case NeonTypeFlags::Poly16:
  1413. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1414. case NeonTypeFlags::Poly64:
  1415. if (IsInt64Long)
  1416. return Context.UnsignedLongTy;
  1417. else
  1418. return Context.UnsignedLongLongTy;
  1419. case NeonTypeFlags::Poly128:
  1420. break;
  1421. case NeonTypeFlags::Float16:
  1422. return Context.HalfTy;
  1423. case NeonTypeFlags::Float32:
  1424. return Context.FloatTy;
  1425. case NeonTypeFlags::Float64:
  1426. return Context.DoubleTy;
  1427. }
  1428. llvm_unreachable("Invalid NeonTypeFlag!");
  1429. }
  1430. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1431. llvm::APSInt Result;
  1432. uint64_t mask = 0;
  1433. unsigned TV = 0;
  1434. int PtrArgNum = -1;
  1435. bool HasConstPtr = false;
  1436. switch (BuiltinID) {
  1437. #define GET_NEON_OVERLOAD_CHECK
  1438. #include "clang/Basic/arm_neon.inc"
  1439. #include "clang/Basic/arm_fp16.inc"
  1440. #undef GET_NEON_OVERLOAD_CHECK
  1441. }
  1442. // For NEON intrinsics which are overloaded on vector element type, validate
  1443. // the immediate which specifies which variant to emit.
  1444. unsigned ImmArg = TheCall->getNumArgs()-1;
  1445. if (mask) {
  1446. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1447. return true;
  1448. TV = Result.getLimitedValue(64);
  1449. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1450. return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
  1451. << TheCall->getArg(ImmArg)->getSourceRange();
  1452. }
  1453. if (PtrArgNum >= 0) {
  1454. // Check that pointer arguments have the specified type.
  1455. Expr *Arg = TheCall->getArg(PtrArgNum);
  1456. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1457. Arg = ICE->getSubExpr();
  1458. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1459. QualType RHSTy = RHS.get()->getType();
  1460. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1461. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1462. Arch == llvm::Triple::aarch64_be;
  1463. bool IsInt64Long =
  1464. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1465. QualType EltTy =
  1466. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1467. if (HasConstPtr)
  1468. EltTy = EltTy.withConst();
  1469. QualType LHSTy = Context.getPointerType(EltTy);
  1470. AssignConvertType ConvTy;
  1471. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1472. if (RHS.isInvalid())
  1473. return true;
  1474. if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
  1475. RHS.get(), AA_Assigning))
  1476. return true;
  1477. }
  1478. // For NEON intrinsics which take an immediate value as part of the
  1479. // instruction, range check them here.
  1480. unsigned i = 0, l = 0, u = 0;
  1481. switch (BuiltinID) {
  1482. default:
  1483. return false;
  1484. #define GET_NEON_IMMEDIATE_CHECK
  1485. #include "clang/Basic/arm_neon.inc"
  1486. #include "clang/Basic/arm_fp16.inc"
  1487. #undef GET_NEON_IMMEDIATE_CHECK
  1488. }
  1489. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1490. }
  1491. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1492. unsigned MaxWidth) {
  1493. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1494. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1495. BuiltinID == ARM::BI__builtin_arm_strex ||
  1496. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1497. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1498. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1499. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1500. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1501. "unexpected ARM builtin");
  1502. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1503. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1504. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1505. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1506. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1507. // Ensure that we have the proper number of arguments.
  1508. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1509. return true;
  1510. // Inspect the pointer argument of the atomic builtin. This should always be
  1511. // a pointer type, whose element is an integral scalar or pointer type.
  1512. // Because it is a pointer type, we don't have to worry about any implicit
  1513. // casts here.
  1514. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1515. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1516. if (PointerArgRes.isInvalid())
  1517. return true;
  1518. PointerArg = PointerArgRes.get();
  1519. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1520. if (!pointerType) {
  1521. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  1522. << PointerArg->getType() << PointerArg->getSourceRange();
  1523. return true;
  1524. }
  1525. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1526. // task is to insert the appropriate casts into the AST. First work out just
  1527. // what the appropriate type is.
  1528. QualType ValType = pointerType->getPointeeType();
  1529. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1530. if (IsLdrex)
  1531. AddrType.addConst();
  1532. // Issue a warning if the cast is dodgy.
  1533. CastKind CastNeeded = CK_NoOp;
  1534. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1535. CastNeeded = CK_BitCast;
  1536. Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
  1537. << PointerArg->getType() << Context.getPointerType(AddrType)
  1538. << AA_Passing << PointerArg->getSourceRange();
  1539. }
  1540. // Finally, do the cast and replace the argument with the corrected version.
  1541. AddrType = Context.getPointerType(AddrType);
  1542. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1543. if (PointerArgRes.isInvalid())
  1544. return true;
  1545. PointerArg = PointerArgRes.get();
  1546. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1547. // In general, we allow ints, floats and pointers to be loaded and stored.
  1548. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1549. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1550. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1551. << PointerArg->getType() << PointerArg->getSourceRange();
  1552. return true;
  1553. }
  1554. // But ARM doesn't have instructions to deal with 128-bit versions.
  1555. if (Context.getTypeSize(ValType) > MaxWidth) {
  1556. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1557. Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
  1558. << PointerArg->getType() << PointerArg->getSourceRange();
  1559. return true;
  1560. }
  1561. switch (ValType.getObjCLifetime()) {
  1562. case Qualifiers::OCL_None:
  1563. case Qualifiers::OCL_ExplicitNone:
  1564. // okay
  1565. break;
  1566. case Qualifiers::OCL_Weak:
  1567. case Qualifiers::OCL_Strong:
  1568. case Qualifiers::OCL_Autoreleasing:
  1569. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  1570. << ValType << PointerArg->getSourceRange();
  1571. return true;
  1572. }
  1573. if (IsLdrex) {
  1574. TheCall->setType(ValType);
  1575. return false;
  1576. }
  1577. // Initialize the argument to be stored.
  1578. ExprResult ValArg = TheCall->getArg(0);
  1579. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1580. Context, ValType, /*consume*/ false);
  1581. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1582. if (ValArg.isInvalid())
  1583. return true;
  1584. TheCall->setArg(0, ValArg.get());
  1585. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1586. // but the custom checker bypasses all default analysis.
  1587. TheCall->setType(Context.IntTy);
  1588. return false;
  1589. }
  1590. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1591. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1592. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1593. BuiltinID == ARM::BI__builtin_arm_strex ||
  1594. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1595. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1596. }
  1597. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1598. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1599. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1600. }
  1601. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1602. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1603. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1604. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1605. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1606. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1607. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1608. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1609. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1610. return true;
  1611. // For intrinsics which take an immediate value as part of the instruction,
  1612. // range check them here.
  1613. // FIXME: VFP Intrinsics should error if VFP not present.
  1614. switch (BuiltinID) {
  1615. default: return false;
  1616. case ARM::BI__builtin_arm_ssat:
  1617. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1618. case ARM::BI__builtin_arm_usat:
  1619. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1620. case ARM::BI__builtin_arm_ssat16:
  1621. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1622. case ARM::BI__builtin_arm_usat16:
  1623. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1624. case ARM::BI__builtin_arm_vcvtr_f:
  1625. case ARM::BI__builtin_arm_vcvtr_d:
  1626. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1627. case ARM::BI__builtin_arm_dmb:
  1628. case ARM::BI__builtin_arm_dsb:
  1629. case ARM::BI__builtin_arm_isb:
  1630. case ARM::BI__builtin_arm_dbg:
  1631. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1632. }
  1633. }
  1634. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1635. CallExpr *TheCall) {
  1636. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1637. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1638. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1639. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1640. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1641. }
  1642. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1643. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1644. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1645. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1646. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1647. }
  1648. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1649. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1650. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1651. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1652. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1653. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1654. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1655. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1656. // Only check the valid encoding range. Any constant in this range would be
  1657. // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
  1658. // an exception for incorrect registers. This matches MSVC behavior.
  1659. if (BuiltinID == AArch64::BI_ReadStatusReg ||
  1660. BuiltinID == AArch64::BI_WriteStatusReg)
  1661. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
  1662. if (BuiltinID == AArch64::BI__getReg)
  1663. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
  1664. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1665. return true;
  1666. // For intrinsics which take an immediate value as part of the instruction,
  1667. // range check them here.
  1668. unsigned i = 0, l = 0, u = 0;
  1669. switch (BuiltinID) {
  1670. default: return false;
  1671. case AArch64::BI__builtin_arm_dmb:
  1672. case AArch64::BI__builtin_arm_dsb:
  1673. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1674. }
  1675. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1676. }
  1677. bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
  1678. struct BuiltinAndString {
  1679. unsigned BuiltinID;
  1680. const char *Str;
  1681. };
  1682. static BuiltinAndString ValidCPU[] = {
  1683. { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
  1684. { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
  1685. { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
  1686. { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
  1687. { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
  1688. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
  1689. { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
  1690. { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
  1691. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
  1692. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
  1693. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
  1694. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
  1695. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
  1696. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
  1697. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
  1698. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
  1699. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
  1700. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
  1701. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
  1702. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
  1703. { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
  1704. { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
  1705. { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
  1706. };
  1707. static BuiltinAndString ValidHVX[] = {
  1708. { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
  1709. { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
  1710. { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
  1711. { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
  1712. { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
  1713. { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
  1714. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
  1715. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
  1716. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
  1717. { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
  1718. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
  1719. { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
  1720. { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
  1721. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
  1722. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
  1723. { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
  1724. { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
  1725. { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
  1726. { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
  1727. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
  1728. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
  1729. { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
  1730. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
  1731. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
  1732. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
  1733. { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
  1734. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
  1735. { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
  1736. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
  1737. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
  1738. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
  1739. { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
  1740. { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
  1741. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
  1742. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
  1743. { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
  1744. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
  1745. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
  1746. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
  1747. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
  1748. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
  1749. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
  1750. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
  1751. { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
  1752. { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
  1753. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
  1754. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
  1755. { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
  1756. { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
  1757. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
  1758. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
  1759. { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
  1760. { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
  1761. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
  1762. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
  1763. { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
  1764. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
  1765. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
  1766. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
  1767. { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
  1768. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
  1769. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
  1770. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
  1771. { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
  1772. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
  1773. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
  1774. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
  1775. { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
  1776. { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
  1777. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
  1778. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
  1779. { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
  1780. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
  1781. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
  1782. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
  1783. { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
  1784. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
  1785. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
  1786. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
  1787. { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
  1788. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
  1789. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
  1790. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
  1791. { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
  1792. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
  1793. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
  1794. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
  1795. { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
  1796. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
  1797. { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
  1798. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
  1799. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
  1800. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
  1801. { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
  1802. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
  1803. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
  1804. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
  1805. { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
  1806. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
  1807. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
  1808. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
  1809. { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
  1810. { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
  1811. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
  1812. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
  1813. { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
  1814. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
  1815. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
  1816. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
  1817. { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
  1818. { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
  1819. { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
  1820. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
  1821. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
  1822. { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
  1823. { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
  1824. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
  1825. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
  1826. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
  1827. { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
  1828. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
  1829. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
  1830. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
  1831. { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
  1832. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
  1833. { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
  1834. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
  1835. { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
  1836. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
  1837. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
  1838. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
  1839. { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
  1840. { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
  1841. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
  1842. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
  1843. { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
  1844. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
  1845. { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
  1846. { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
  1847. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
  1848. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
  1849. { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
  1850. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
  1851. { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
  1852. { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
  1853. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
  1854. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
  1855. { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
  1856. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
  1857. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
  1858. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
  1859. { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
  1860. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
  1861. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
  1862. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
  1863. { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
  1864. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
  1865. { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
  1866. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
  1867. { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
  1868. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
  1869. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
  1870. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
  1871. { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
  1872. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
  1873. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
  1874. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
  1875. { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
  1876. { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
  1877. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
  1878. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
  1879. { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
  1880. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
  1881. { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
  1882. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
  1883. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
  1884. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
  1885. { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
  1886. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
  1887. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
  1888. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
  1889. { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
  1890. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
  1891. { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
  1892. { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
  1893. { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
  1894. { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
  1895. { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
  1896. { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
  1897. { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
  1898. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
  1899. { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
  1900. { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
  1901. { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
  1902. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
  1903. { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
  1904. { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
  1905. { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
  1906. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
  1907. { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
  1908. { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
  1909. { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
  1910. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
  1911. { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
  1912. { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
  1913. { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
  1914. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
  1915. { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
  1916. { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
  1917. { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
  1918. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
  1919. { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
  1920. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
  1921. { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
  1922. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
  1923. { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
  1924. { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
  1925. { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
  1926. { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
  1927. { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
  1928. { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
  1929. { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
  1930. { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
  1931. { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
  1932. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
  1933. { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
  1934. { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
  1935. { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
  1936. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
  1937. { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
  1938. { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
  1939. { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
  1940. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
  1941. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
  1942. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
  1943. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
  1944. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
  1945. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
  1946. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
  1947. { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
  1948. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
  1949. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
  1950. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
  1951. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
  1952. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
  1953. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
  1954. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
  1955. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
  1956. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
  1957. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
  1958. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
  1959. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
  1960. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
  1961. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
  1962. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
  1963. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
  1964. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
  1965. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
  1966. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
  1967. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
  1968. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
  1969. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
  1970. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
  1971. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
  1972. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
  1973. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
  1974. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
  1975. { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
  1976. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
  1977. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
  1978. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
  1979. { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
  1980. { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
  1981. { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
  1982. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
  1983. { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
  1984. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
  1985. { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
  1986. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
  1987. { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
  1988. { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
  1989. { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
  1990. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
  1991. { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
  1992. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
  1993. { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
  1994. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
  1995. { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
  1996. { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
  1997. { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
  1998. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
  1999. { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
  2000. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
  2001. { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
  2002. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
  2003. { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
  2004. { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
  2005. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
  2006. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
  2007. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
  2008. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
  2009. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
  2010. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
  2011. { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
  2012. { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
  2013. { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
  2014. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
  2015. { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
  2016. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
  2017. { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
  2018. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
  2019. { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
  2020. { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
  2021. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
  2022. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
  2023. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
  2024. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
  2025. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
  2026. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
  2027. { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
  2028. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
  2029. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
  2030. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
  2031. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
  2032. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
  2033. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
  2034. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
  2035. { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
  2036. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
  2037. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
  2038. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
  2039. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
  2040. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
  2041. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
  2042. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
  2043. { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
  2044. { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
  2045. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
  2046. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
  2047. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
  2048. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
  2049. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
  2050. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
  2051. { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
  2052. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
  2053. { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
  2054. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
  2055. { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
  2056. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
  2057. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
  2058. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
  2059. { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
  2060. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
  2061. { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
  2062. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
  2063. { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
  2064. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
  2065. { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
  2066. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
  2067. { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
  2068. { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
  2069. { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
  2070. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
  2071. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
  2072. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
  2073. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
  2074. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
  2075. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
  2076. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
  2077. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
  2078. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
  2079. { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
  2080. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
  2081. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
  2082. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
  2083. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
  2084. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
  2085. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
  2086. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
  2087. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
  2088. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
  2089. { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
  2090. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
  2091. { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
  2092. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
  2093. { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
  2094. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
  2095. { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
  2096. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
  2097. { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
  2098. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
  2099. { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
  2100. { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
  2101. { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
  2102. { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
  2103. { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
  2104. { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
  2105. { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
  2106. { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
  2107. { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
  2108. { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
  2109. { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
  2110. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
  2111. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
  2112. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
  2113. { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
  2114. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
  2115. { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
  2116. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
  2117. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
  2118. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
  2119. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
  2120. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
  2121. { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
  2122. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
  2123. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
  2124. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
  2125. { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
  2126. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
  2127. { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
  2128. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
  2129. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
  2130. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
  2131. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
  2132. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
  2133. { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
  2134. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
  2135. { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
  2136. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
  2137. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
  2138. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
  2139. { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
  2140. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
  2141. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
  2142. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
  2143. { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
  2144. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
  2145. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
  2146. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
  2147. { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
  2148. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
  2149. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
  2150. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
  2151. { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
  2152. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
  2153. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
  2154. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
  2155. { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
  2156. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
  2157. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
  2158. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
  2159. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
  2160. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
  2161. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
  2162. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
  2163. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
  2164. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
  2165. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
  2166. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
  2167. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
  2168. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
  2169. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
  2170. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
  2171. { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
  2172. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
  2173. { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
  2174. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
  2175. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
  2176. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
  2177. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
  2178. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
  2179. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
  2180. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
  2181. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
  2182. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
  2183. { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
  2184. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
  2185. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
  2186. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
  2187. { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
  2188. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
  2189. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
  2190. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
  2191. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
  2192. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
  2193. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
  2194. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
  2195. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
  2196. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
  2197. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
  2198. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
  2199. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
  2200. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
  2201. { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
  2202. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
  2203. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
  2204. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
  2205. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
  2206. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
  2207. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
  2208. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
  2209. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
  2210. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
  2211. { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
  2212. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
  2213. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
  2214. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
  2215. { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
  2216. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
  2217. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
  2218. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
  2219. { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
  2220. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
  2221. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
  2222. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
  2223. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
  2224. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
  2225. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
  2226. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
  2227. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
  2228. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
  2229. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
  2230. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
  2231. { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
  2232. { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
  2233. { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
  2234. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
  2235. { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
  2236. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
  2237. { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
  2238. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
  2239. { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
  2240. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
  2241. { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
  2242. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
  2243. { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
  2244. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
  2245. { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
  2246. { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
  2247. { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
  2248. { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
  2249. { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
  2250. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
  2251. { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
  2252. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
  2253. { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
  2254. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
  2255. { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
  2256. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
  2257. { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
  2258. { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
  2259. { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
  2260. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
  2261. { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
  2262. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
  2263. { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
  2264. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
  2265. { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
  2266. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
  2267. { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
  2268. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
  2269. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
  2270. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
  2271. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
  2272. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
  2273. { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
  2274. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
  2275. { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
  2276. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
  2277. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
  2278. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
  2279. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
  2280. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
  2281. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
  2282. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
  2283. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
  2284. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
  2285. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
  2286. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
  2287. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
  2288. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
  2289. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
  2290. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
  2291. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
  2292. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
  2293. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
  2294. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
  2295. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
  2296. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
  2297. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
  2298. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
  2299. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
  2300. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
  2301. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
  2302. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
  2303. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
  2304. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
  2305. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
  2306. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
  2307. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
  2308. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
  2309. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
  2310. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
  2311. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
  2312. { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
  2313. { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
  2314. { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
  2315. { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
  2316. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
  2317. { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
  2318. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
  2319. { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
  2320. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
  2321. { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
  2322. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
  2323. { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
  2324. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
  2325. { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
  2326. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
  2327. { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
  2328. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
  2329. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
  2330. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
  2331. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
  2332. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
  2333. { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
  2334. { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
  2335. { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
  2336. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
  2337. { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
  2338. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
  2339. { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
  2340. { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
  2341. { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
  2342. { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
  2343. { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
  2344. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
  2345. { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
  2346. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
  2347. { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
  2348. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
  2349. { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
  2350. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
  2351. { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
  2352. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
  2353. { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
  2354. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
  2355. { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
  2356. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
  2357. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
  2358. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
  2359. { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
  2360. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
  2361. { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
  2362. { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
  2363. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
  2364. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
  2365. { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
  2366. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
  2367. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
  2368. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
  2369. { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
  2370. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
  2371. { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
  2372. { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
  2373. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
  2374. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
  2375. { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
  2376. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
  2377. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
  2378. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
  2379. { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
  2380. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
  2381. { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
  2382. { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
  2383. { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
  2384. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
  2385. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
  2386. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
  2387. { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
  2388. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
  2389. { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
  2390. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
  2391. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
  2392. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
  2393. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
  2394. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
  2395. { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
  2396. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
  2397. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
  2398. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
  2399. { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
  2400. { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
  2401. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
  2402. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
  2403. { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
  2404. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
  2405. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
  2406. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
  2407. { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
  2408. { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
  2409. { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
  2410. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
  2411. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
  2412. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
  2413. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
  2414. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
  2415. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
  2416. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
  2417. { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
  2418. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
  2419. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
  2420. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
  2421. { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
  2422. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
  2423. { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
  2424. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
  2425. { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
  2426. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
  2427. { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
  2428. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
  2429. { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
  2430. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
  2431. { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
  2432. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
  2433. { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
  2434. { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
  2435. { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
  2436. { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
  2437. { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
  2438. { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
  2439. { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
  2440. };
  2441. // Sort the tables on first execution so we can binary search them.
  2442. auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
  2443. return LHS.BuiltinID < RHS.BuiltinID;
  2444. };
  2445. static const bool SortOnce =
  2446. (llvm::sort(ValidCPU, SortCmp),
  2447. llvm::sort(ValidHVX, SortCmp), true);
  2448. (void)SortOnce;
  2449. auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
  2450. return BI.BuiltinID < BuiltinID;
  2451. };
  2452. const TargetInfo &TI = Context.getTargetInfo();
  2453. const BuiltinAndString *FC =
  2454. std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
  2455. LowerBoundCmp);
  2456. if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
  2457. const TargetOptions &Opts = TI.getTargetOpts();
  2458. StringRef CPU = Opts.CPU;
  2459. if (!CPU.empty()) {
  2460. assert(CPU.startswith("hexagon") && "Unexpected CPU name");
  2461. CPU.consume_front("hexagon");
  2462. SmallVector<StringRef, 3> CPUs;
  2463. StringRef(FC->Str).split(CPUs, ',');
  2464. if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
  2465. return Diag(TheCall->getBeginLoc(),
  2466. diag::err_hexagon_builtin_unsupported_cpu);
  2467. }
  2468. }
  2469. const BuiltinAndString *FH =
  2470. std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
  2471. LowerBoundCmp);
  2472. if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
  2473. if (!TI.hasFeature("hvx"))
  2474. return Diag(TheCall->getBeginLoc(),
  2475. diag::err_hexagon_builtin_requires_hvx);
  2476. SmallVector<StringRef, 3> HVXs;
  2477. StringRef(FH->Str).split(HVXs, ',');
  2478. bool IsValid = llvm::any_of(HVXs,
  2479. [&TI] (StringRef V) {
  2480. std::string F = "hvx" + V.str();
  2481. return TI.hasFeature(F);
  2482. });
  2483. if (!IsValid)
  2484. return Diag(TheCall->getBeginLoc(),
  2485. diag::err_hexagon_builtin_unsupported_hvx);
  2486. }
  2487. return false;
  2488. }
  2489. bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
  2490. struct ArgInfo {
  2491. uint8_t OpNum;
  2492. bool IsSigned;
  2493. uint8_t BitWidth;
  2494. uint8_t Align;
  2495. };
  2496. struct BuiltinInfo {
  2497. unsigned BuiltinID;
  2498. ArgInfo Infos[2];
  2499. };
  2500. static BuiltinInfo Infos[] = {
  2501. { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
  2502. { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
  2503. { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
  2504. { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
  2505. { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
  2506. { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
  2507. { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
  2508. { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
  2509. { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
  2510. { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
  2511. { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
  2512. { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
  2513. { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
  2514. { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
  2515. { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
  2516. { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
  2517. { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
  2518. { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
  2519. { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
  2520. { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
  2521. { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
  2522. { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
  2523. { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
  2524. { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
  2525. { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
  2526. { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
  2527. { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
  2528. { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
  2529. { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
  2530. { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
  2531. { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
  2532. { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
  2533. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
  2534. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
  2535. { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
  2536. { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
  2537. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
  2538. { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
  2539. { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
  2540. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
  2541. { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
  2542. { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
  2543. { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
  2544. { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
  2545. { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
  2546. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
  2547. { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
  2548. { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
  2549. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
  2550. { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
  2551. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
  2552. { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
  2553. { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
  2554. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
  2555. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
  2556. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
  2557. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
  2558. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
  2559. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
  2560. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
  2561. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
  2562. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
  2563. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
  2564. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
  2565. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
  2566. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
  2567. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
  2568. { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
  2569. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
  2570. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
  2571. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
  2572. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
  2573. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
  2574. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
  2575. {{ 1, false, 6, 0 }} },
  2576. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
  2577. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
  2578. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
  2579. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
  2580. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
  2581. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
  2582. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
  2583. {{ 1, false, 5, 0 }} },
  2584. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
  2585. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
  2586. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
  2587. { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
  2588. { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
  2589. { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
  2590. { 2, false, 5, 0 }} },
  2591. { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
  2592. { 2, false, 6, 0 }} },
  2593. { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
  2594. { 3, false, 5, 0 }} },
  2595. { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
  2596. { 3, false, 6, 0 }} },
  2597. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
  2598. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
  2599. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
  2600. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
  2601. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
  2602. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
  2603. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
  2604. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
  2605. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
  2606. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
  2607. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
  2608. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
  2609. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
  2610. { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
  2611. { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
  2612. { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
  2613. {{ 2, false, 4, 0 },
  2614. { 3, false, 5, 0 }} },
  2615. { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
  2616. {{ 2, false, 4, 0 },
  2617. { 3, false, 5, 0 }} },
  2618. { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
  2619. {{ 2, false, 4, 0 },
  2620. { 3, false, 5, 0 }} },
  2621. { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
  2622. {{ 2, false, 4, 0 },
  2623. { 3, false, 5, 0 }} },
  2624. { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
  2625. { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
  2626. { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
  2627. { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
  2628. { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
  2629. { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
  2630. { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
  2631. { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
  2632. { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
  2633. { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
  2634. { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
  2635. { 2, false, 5, 0 }} },
  2636. { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
  2637. { 2, false, 6, 0 }} },
  2638. { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
  2639. { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
  2640. { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
  2641. { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
  2642. { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
  2643. { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
  2644. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
  2645. { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
  2646. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
  2647. {{ 1, false, 4, 0 }} },
  2648. { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
  2649. { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
  2650. {{ 1, false, 4, 0 }} },
  2651. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
  2652. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
  2653. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
  2654. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
  2655. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
  2656. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
  2657. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
  2658. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
  2659. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
  2660. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
  2661. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
  2662. { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
  2663. { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
  2664. { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
  2665. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
  2666. { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
  2667. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
  2668. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
  2669. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
  2670. { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
  2671. {{ 3, false, 1, 0 }} },
  2672. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
  2673. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
  2674. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
  2675. { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
  2676. {{ 3, false, 1, 0 }} },
  2677. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
  2678. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
  2679. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
  2680. { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
  2681. {{ 3, false, 1, 0 }} },
  2682. };
  2683. // Use a dynamically initialized static to sort the table exactly once on
  2684. // first run.
  2685. static const bool SortOnce =
  2686. (llvm::sort(Infos,
  2687. [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
  2688. return LHS.BuiltinID < RHS.BuiltinID;
  2689. }),
  2690. true);
  2691. (void)SortOnce;
  2692. const BuiltinInfo *F =
  2693. std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
  2694. [](const BuiltinInfo &BI, unsigned BuiltinID) {
  2695. return BI.BuiltinID < BuiltinID;
  2696. });
  2697. if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
  2698. return false;
  2699. bool Error = false;
  2700. for (const ArgInfo &A : F->Infos) {
  2701. // Ignore empty ArgInfo elements.
  2702. if (A.BitWidth == 0)
  2703. continue;
  2704. int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
  2705. int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
  2706. if (!A.Align) {
  2707. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
  2708. } else {
  2709. unsigned M = 1 << A.Align;
  2710. Min *= M;
  2711. Max *= M;
  2712. Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
  2713. SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
  2714. }
  2715. }
  2716. return Error;
  2717. }
  2718. bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
  2719. CallExpr *TheCall) {
  2720. return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
  2721. CheckHexagonBuiltinArgument(BuiltinID, TheCall);
  2722. }
  2723. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  2724. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  2725. // ordering for DSP is unspecified. MSA is ordered by the data format used
  2726. // by the underlying instruction i.e., df/m, df/n and then by size.
  2727. //
  2728. // FIXME: The size tests here should instead be tablegen'd along with the
  2729. // definitions from include/clang/Basic/BuiltinsMips.def.
  2730. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  2731. // be too.
  2732. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2733. unsigned i = 0, l = 0, u = 0, m = 0;
  2734. switch (BuiltinID) {
  2735. default: return false;
  2736. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  2737. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  2738. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  2739. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  2740. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  2741. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  2742. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  2743. // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
  2744. // df/m field.
  2745. // These intrinsics take an unsigned 3 bit immediate.
  2746. case Mips::BI__builtin_msa_bclri_b:
  2747. case Mips::BI__builtin_msa_bnegi_b:
  2748. case Mips::BI__builtin_msa_bseti_b:
  2749. case Mips::BI__builtin_msa_sat_s_b:
  2750. case Mips::BI__builtin_msa_sat_u_b:
  2751. case Mips::BI__builtin_msa_slli_b:
  2752. case Mips::BI__builtin_msa_srai_b:
  2753. case Mips::BI__builtin_msa_srari_b:
  2754. case Mips::BI__builtin_msa_srli_b:
  2755. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  2756. case Mips::BI__builtin_msa_binsli_b:
  2757. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  2758. // These intrinsics take an unsigned 4 bit immediate.
  2759. case Mips::BI__builtin_msa_bclri_h:
  2760. case Mips::BI__builtin_msa_bnegi_h:
  2761. case Mips::BI__builtin_msa_bseti_h:
  2762. case Mips::BI__builtin_msa_sat_s_h:
  2763. case Mips::BI__builtin_msa_sat_u_h:
  2764. case Mips::BI__builtin_msa_slli_h:
  2765. case Mips::BI__builtin_msa_srai_h:
  2766. case Mips::BI__builtin_msa_srari_h:
  2767. case Mips::BI__builtin_msa_srli_h:
  2768. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  2769. case Mips::BI__builtin_msa_binsli_h:
  2770. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  2771. // These intrinsics take an unsigned 5 bit immediate.
  2772. // The first block of intrinsics actually have an unsigned 5 bit field,
  2773. // not a df/n field.
  2774. case Mips::BI__builtin_msa_clei_u_b:
  2775. case Mips::BI__builtin_msa_clei_u_h:
  2776. case Mips::BI__builtin_msa_clei_u_w:
  2777. case Mips::BI__builtin_msa_clei_u_d:
  2778. case Mips::BI__builtin_msa_clti_u_b:
  2779. case Mips::BI__builtin_msa_clti_u_h:
  2780. case Mips::BI__builtin_msa_clti_u_w:
  2781. case Mips::BI__builtin_msa_clti_u_d:
  2782. case Mips::BI__builtin_msa_maxi_u_b:
  2783. case Mips::BI__builtin_msa_maxi_u_h:
  2784. case Mips::BI__builtin_msa_maxi_u_w:
  2785. case Mips::BI__builtin_msa_maxi_u_d:
  2786. case Mips::BI__builtin_msa_mini_u_b:
  2787. case Mips::BI__builtin_msa_mini_u_h:
  2788. case Mips::BI__builtin_msa_mini_u_w:
  2789. case Mips::BI__builtin_msa_mini_u_d:
  2790. case Mips::BI__builtin_msa_addvi_b:
  2791. case Mips::BI__builtin_msa_addvi_h:
  2792. case Mips::BI__builtin_msa_addvi_w:
  2793. case Mips::BI__builtin_msa_addvi_d:
  2794. case Mips::BI__builtin_msa_bclri_w:
  2795. case Mips::BI__builtin_msa_bnegi_w:
  2796. case Mips::BI__builtin_msa_bseti_w:
  2797. case Mips::BI__builtin_msa_sat_s_w:
  2798. case Mips::BI__builtin_msa_sat_u_w:
  2799. case Mips::BI__builtin_msa_slli_w:
  2800. case Mips::BI__builtin_msa_srai_w:
  2801. case Mips::BI__builtin_msa_srari_w:
  2802. case Mips::BI__builtin_msa_srli_w:
  2803. case Mips::BI__builtin_msa_srlri_w:
  2804. case Mips::BI__builtin_msa_subvi_b:
  2805. case Mips::BI__builtin_msa_subvi_h:
  2806. case Mips::BI__builtin_msa_subvi_w:
  2807. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  2808. case Mips::BI__builtin_msa_binsli_w:
  2809. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  2810. // These intrinsics take an unsigned 6 bit immediate.
  2811. case Mips::BI__builtin_msa_bclri_d:
  2812. case Mips::BI__builtin_msa_bnegi_d:
  2813. case Mips::BI__builtin_msa_bseti_d:
  2814. case Mips::BI__builtin_msa_sat_s_d:
  2815. case Mips::BI__builtin_msa_sat_u_d:
  2816. case Mips::BI__builtin_msa_slli_d:
  2817. case Mips::BI__builtin_msa_srai_d:
  2818. case Mips::BI__builtin_msa_srari_d:
  2819. case Mips::BI__builtin_msa_srli_d:
  2820. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  2821. case Mips::BI__builtin_msa_binsli_d:
  2822. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  2823. // These intrinsics take a signed 5 bit immediate.
  2824. case Mips::BI__builtin_msa_ceqi_b:
  2825. case Mips::BI__builtin_msa_ceqi_h:
  2826. case Mips::BI__builtin_msa_ceqi_w:
  2827. case Mips::BI__builtin_msa_ceqi_d:
  2828. case Mips::BI__builtin_msa_clti_s_b:
  2829. case Mips::BI__builtin_msa_clti_s_h:
  2830. case Mips::BI__builtin_msa_clti_s_w:
  2831. case Mips::BI__builtin_msa_clti_s_d:
  2832. case Mips::BI__builtin_msa_clei_s_b:
  2833. case Mips::BI__builtin_msa_clei_s_h:
  2834. case Mips::BI__builtin_msa_clei_s_w:
  2835. case Mips::BI__builtin_msa_clei_s_d:
  2836. case Mips::BI__builtin_msa_maxi_s_b:
  2837. case Mips::BI__builtin_msa_maxi_s_h:
  2838. case Mips::BI__builtin_msa_maxi_s_w:
  2839. case Mips::BI__builtin_msa_maxi_s_d:
  2840. case Mips::BI__builtin_msa_mini_s_b:
  2841. case Mips::BI__builtin_msa_mini_s_h:
  2842. case Mips::BI__builtin_msa_mini_s_w:
  2843. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  2844. // These intrinsics take an unsigned 8 bit immediate.
  2845. case Mips::BI__builtin_msa_andi_b:
  2846. case Mips::BI__builtin_msa_nori_b:
  2847. case Mips::BI__builtin_msa_ori_b:
  2848. case Mips::BI__builtin_msa_shf_b:
  2849. case Mips::BI__builtin_msa_shf_h:
  2850. case Mips::BI__builtin_msa_shf_w:
  2851. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  2852. case Mips::BI__builtin_msa_bseli_b:
  2853. case Mips::BI__builtin_msa_bmnzi_b:
  2854. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  2855. // df/n format
  2856. // These intrinsics take an unsigned 4 bit immediate.
  2857. case Mips::BI__builtin_msa_copy_s_b:
  2858. case Mips::BI__builtin_msa_copy_u_b:
  2859. case Mips::BI__builtin_msa_insve_b:
  2860. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  2861. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  2862. // These intrinsics take an unsigned 3 bit immediate.
  2863. case Mips::BI__builtin_msa_copy_s_h:
  2864. case Mips::BI__builtin_msa_copy_u_h:
  2865. case Mips::BI__builtin_msa_insve_h:
  2866. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  2867. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  2868. // These intrinsics take an unsigned 2 bit immediate.
  2869. case Mips::BI__builtin_msa_copy_s_w:
  2870. case Mips::BI__builtin_msa_copy_u_w:
  2871. case Mips::BI__builtin_msa_insve_w:
  2872. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  2873. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  2874. // These intrinsics take an unsigned 1 bit immediate.
  2875. case Mips::BI__builtin_msa_copy_s_d:
  2876. case Mips::BI__builtin_msa_copy_u_d:
  2877. case Mips::BI__builtin_msa_insve_d:
  2878. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  2879. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  2880. // Memory offsets and immediate loads.
  2881. // These intrinsics take a signed 10 bit immediate.
  2882. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  2883. case Mips::BI__builtin_msa_ldi_h:
  2884. case Mips::BI__builtin_msa_ldi_w:
  2885. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  2886. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
  2887. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
  2888. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
  2889. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
  2890. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
  2891. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
  2892. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
  2893. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
  2894. }
  2895. if (!m)
  2896. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2897. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  2898. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  2899. }
  2900. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2901. unsigned i = 0, l = 0, u = 0;
  2902. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  2903. BuiltinID == PPC::BI__builtin_divdeu ||
  2904. BuiltinID == PPC::BI__builtin_bpermd;
  2905. bool IsTarget64Bit = Context.getTargetInfo()
  2906. .getTypeWidth(Context
  2907. .getTargetInfo()
  2908. .getIntPtrType()) == 64;
  2909. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  2910. BuiltinID == PPC::BI__builtin_divweu ||
  2911. BuiltinID == PPC::BI__builtin_divde ||
  2912. BuiltinID == PPC::BI__builtin_divdeu;
  2913. if (Is64BitBltin && !IsTarget64Bit)
  2914. return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
  2915. << TheCall->getSourceRange();
  2916. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  2917. (BuiltinID == PPC::BI__builtin_bpermd &&
  2918. !Context.getTargetInfo().hasFeature("bpermd")))
  2919. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2920. << TheCall->getSourceRange();
  2921. auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
  2922. if (!Context.getTargetInfo().hasFeature("vsx"))
  2923. return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
  2924. << TheCall->getSourceRange();
  2925. return false;
  2926. };
  2927. switch (BuiltinID) {
  2928. default: return false;
  2929. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  2930. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  2931. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  2932. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2933. case PPC::BI__builtin_tbegin:
  2934. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  2935. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  2936. case PPC::BI__builtin_tabortwc:
  2937. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  2938. case PPC::BI__builtin_tabortwci:
  2939. case PPC::BI__builtin_tabortdci:
  2940. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  2941. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  2942. case PPC::BI__builtin_vsx_xxpermdi:
  2943. case PPC::BI__builtin_vsx_xxsldwi:
  2944. return SemaBuiltinVSX(TheCall);
  2945. case PPC::BI__builtin_unpack_vector_int128:
  2946. return SemaVSXCheck(TheCall) ||
  2947. SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  2948. case PPC::BI__builtin_pack_vector_int128:
  2949. return SemaVSXCheck(TheCall);
  2950. }
  2951. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2952. }
  2953. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  2954. CallExpr *TheCall) {
  2955. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  2956. Expr *Arg = TheCall->getArg(0);
  2957. llvm::APSInt AbortCode(32);
  2958. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  2959. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  2960. return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
  2961. << Arg->getSourceRange();
  2962. }
  2963. // For intrinsics which take an immediate value as part of the instruction,
  2964. // range check them here.
  2965. unsigned i = 0, l = 0, u = 0;
  2966. switch (BuiltinID) {
  2967. default: return false;
  2968. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  2969. case SystemZ::BI__builtin_s390_verimb:
  2970. case SystemZ::BI__builtin_s390_verimh:
  2971. case SystemZ::BI__builtin_s390_verimf:
  2972. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  2973. case SystemZ::BI__builtin_s390_vfaeb:
  2974. case SystemZ::BI__builtin_s390_vfaeh:
  2975. case SystemZ::BI__builtin_s390_vfaef:
  2976. case SystemZ::BI__builtin_s390_vfaebs:
  2977. case SystemZ::BI__builtin_s390_vfaehs:
  2978. case SystemZ::BI__builtin_s390_vfaefs:
  2979. case SystemZ::BI__builtin_s390_vfaezb:
  2980. case SystemZ::BI__builtin_s390_vfaezh:
  2981. case SystemZ::BI__builtin_s390_vfaezf:
  2982. case SystemZ::BI__builtin_s390_vfaezbs:
  2983. case SystemZ::BI__builtin_s390_vfaezhs:
  2984. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  2985. case SystemZ::BI__builtin_s390_vfisb:
  2986. case SystemZ::BI__builtin_s390_vfidb:
  2987. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  2988. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  2989. case SystemZ::BI__builtin_s390_vftcisb:
  2990. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  2991. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  2992. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  2993. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  2994. case SystemZ::BI__builtin_s390_vstrcb:
  2995. case SystemZ::BI__builtin_s390_vstrch:
  2996. case SystemZ::BI__builtin_s390_vstrcf:
  2997. case SystemZ::BI__builtin_s390_vstrczb:
  2998. case SystemZ::BI__builtin_s390_vstrczh:
  2999. case SystemZ::BI__builtin_s390_vstrczf:
  3000. case SystemZ::BI__builtin_s390_vstrcbs:
  3001. case SystemZ::BI__builtin_s390_vstrchs:
  3002. case SystemZ::BI__builtin_s390_vstrcfs:
  3003. case SystemZ::BI__builtin_s390_vstrczbs:
  3004. case SystemZ::BI__builtin_s390_vstrczhs:
  3005. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  3006. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  3007. case SystemZ::BI__builtin_s390_vfminsb:
  3008. case SystemZ::BI__builtin_s390_vfmaxsb:
  3009. case SystemZ::BI__builtin_s390_vfmindb:
  3010. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  3011. }
  3012. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  3013. }
  3014. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  3015. /// This checks that the target supports __builtin_cpu_supports and
  3016. /// that the string argument is constant and valid.
  3017. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  3018. Expr *Arg = TheCall->getArg(0);
  3019. // Check if the argument is a string literal.
  3020. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3021. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3022. << Arg->getSourceRange();
  3023. // Check the contents of the string.
  3024. StringRef Feature =
  3025. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3026. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  3027. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
  3028. << Arg->getSourceRange();
  3029. return false;
  3030. }
  3031. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  3032. /// This checks that the target supports __builtin_cpu_is and
  3033. /// that the string argument is constant and valid.
  3034. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  3035. Expr *Arg = TheCall->getArg(0);
  3036. // Check if the argument is a string literal.
  3037. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  3038. return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  3039. << Arg->getSourceRange();
  3040. // Check the contents of the string.
  3041. StringRef Feature =
  3042. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  3043. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  3044. return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
  3045. << Arg->getSourceRange();
  3046. return false;
  3047. }
  3048. // Check if the rounding mode is legal.
  3049. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  3050. // Indicates if this instruction has rounding control or just SAE.
  3051. bool HasRC = false;
  3052. unsigned ArgNum = 0;
  3053. switch (BuiltinID) {
  3054. default:
  3055. return false;
  3056. case X86::BI__builtin_ia32_vcvttsd2si32:
  3057. case X86::BI__builtin_ia32_vcvttsd2si64:
  3058. case X86::BI__builtin_ia32_vcvttsd2usi32:
  3059. case X86::BI__builtin_ia32_vcvttsd2usi64:
  3060. case X86::BI__builtin_ia32_vcvttss2si32:
  3061. case X86::BI__builtin_ia32_vcvttss2si64:
  3062. case X86::BI__builtin_ia32_vcvttss2usi32:
  3063. case X86::BI__builtin_ia32_vcvttss2usi64:
  3064. ArgNum = 1;
  3065. break;
  3066. case X86::BI__builtin_ia32_maxpd512:
  3067. case X86::BI__builtin_ia32_maxps512:
  3068. case X86::BI__builtin_ia32_minpd512:
  3069. case X86::BI__builtin_ia32_minps512:
  3070. ArgNum = 2;
  3071. break;
  3072. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  3073. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  3074. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  3075. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  3076. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  3077. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  3078. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  3079. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  3080. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  3081. case X86::BI__builtin_ia32_exp2pd_mask:
  3082. case X86::BI__builtin_ia32_exp2ps_mask:
  3083. case X86::BI__builtin_ia32_getexppd512_mask:
  3084. case X86::BI__builtin_ia32_getexpps512_mask:
  3085. case X86::BI__builtin_ia32_rcp28pd_mask:
  3086. case X86::BI__builtin_ia32_rcp28ps_mask:
  3087. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  3088. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  3089. case X86::BI__builtin_ia32_vcomisd:
  3090. case X86::BI__builtin_ia32_vcomiss:
  3091. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  3092. ArgNum = 3;
  3093. break;
  3094. case X86::BI__builtin_ia32_cmppd512_mask:
  3095. case X86::BI__builtin_ia32_cmpps512_mask:
  3096. case X86::BI__builtin_ia32_cmpsd_mask:
  3097. case X86::BI__builtin_ia32_cmpss_mask:
  3098. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  3099. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  3100. case X86::BI__builtin_ia32_getexpss128_round_mask:
  3101. case X86::BI__builtin_ia32_maxsd_round_mask:
  3102. case X86::BI__builtin_ia32_maxss_round_mask:
  3103. case X86::BI__builtin_ia32_minsd_round_mask:
  3104. case X86::BI__builtin_ia32_minss_round_mask:
  3105. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  3106. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  3107. case X86::BI__builtin_ia32_reducepd512_mask:
  3108. case X86::BI__builtin_ia32_reduceps512_mask:
  3109. case X86::BI__builtin_ia32_rndscalepd_mask:
  3110. case X86::BI__builtin_ia32_rndscaleps_mask:
  3111. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  3112. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  3113. ArgNum = 4;
  3114. break;
  3115. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3116. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3117. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3118. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3119. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3120. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3121. case X86::BI__builtin_ia32_fixupimmss_mask:
  3122. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3123. case X86::BI__builtin_ia32_rangepd512_mask:
  3124. case X86::BI__builtin_ia32_rangeps512_mask:
  3125. case X86::BI__builtin_ia32_rangesd128_round_mask:
  3126. case X86::BI__builtin_ia32_rangess128_round_mask:
  3127. case X86::BI__builtin_ia32_reducesd_mask:
  3128. case X86::BI__builtin_ia32_reducess_mask:
  3129. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3130. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3131. ArgNum = 5;
  3132. break;
  3133. case X86::BI__builtin_ia32_vcvtsd2si64:
  3134. case X86::BI__builtin_ia32_vcvtsd2si32:
  3135. case X86::BI__builtin_ia32_vcvtsd2usi32:
  3136. case X86::BI__builtin_ia32_vcvtsd2usi64:
  3137. case X86::BI__builtin_ia32_vcvtss2si32:
  3138. case X86::BI__builtin_ia32_vcvtss2si64:
  3139. case X86::BI__builtin_ia32_vcvtss2usi32:
  3140. case X86::BI__builtin_ia32_vcvtss2usi64:
  3141. case X86::BI__builtin_ia32_sqrtpd512:
  3142. case X86::BI__builtin_ia32_sqrtps512:
  3143. ArgNum = 1;
  3144. HasRC = true;
  3145. break;
  3146. case X86::BI__builtin_ia32_addpd512:
  3147. case X86::BI__builtin_ia32_addps512:
  3148. case X86::BI__builtin_ia32_divpd512:
  3149. case X86::BI__builtin_ia32_divps512:
  3150. case X86::BI__builtin_ia32_mulpd512:
  3151. case X86::BI__builtin_ia32_mulps512:
  3152. case X86::BI__builtin_ia32_subpd512:
  3153. case X86::BI__builtin_ia32_subps512:
  3154. case X86::BI__builtin_ia32_cvtsi2sd64:
  3155. case X86::BI__builtin_ia32_cvtsi2ss32:
  3156. case X86::BI__builtin_ia32_cvtsi2ss64:
  3157. case X86::BI__builtin_ia32_cvtusi2sd64:
  3158. case X86::BI__builtin_ia32_cvtusi2ss32:
  3159. case X86::BI__builtin_ia32_cvtusi2ss64:
  3160. ArgNum = 2;
  3161. HasRC = true;
  3162. break;
  3163. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  3164. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  3165. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  3166. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  3167. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  3168. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  3169. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  3170. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  3171. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  3172. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  3173. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  3174. ArgNum = 3;
  3175. HasRC = true;
  3176. break;
  3177. case X86::BI__builtin_ia32_addss_round_mask:
  3178. case X86::BI__builtin_ia32_addsd_round_mask:
  3179. case X86::BI__builtin_ia32_divss_round_mask:
  3180. case X86::BI__builtin_ia32_divsd_round_mask:
  3181. case X86::BI__builtin_ia32_mulss_round_mask:
  3182. case X86::BI__builtin_ia32_mulsd_round_mask:
  3183. case X86::BI__builtin_ia32_subss_round_mask:
  3184. case X86::BI__builtin_ia32_subsd_round_mask:
  3185. case X86::BI__builtin_ia32_scalefpd512_mask:
  3186. case X86::BI__builtin_ia32_scalefps512_mask:
  3187. case X86::BI__builtin_ia32_scalefsd_round_mask:
  3188. case X86::BI__builtin_ia32_scalefss_round_mask:
  3189. case X86::BI__builtin_ia32_getmantpd512_mask:
  3190. case X86::BI__builtin_ia32_getmantps512_mask:
  3191. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  3192. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  3193. case X86::BI__builtin_ia32_sqrtss_round_mask:
  3194. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  3195. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  3196. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  3197. case X86::BI__builtin_ia32_vfmaddss3_mask:
  3198. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  3199. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  3200. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  3201. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  3202. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  3203. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  3204. case X86::BI__builtin_ia32_vfmaddps512_mask:
  3205. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  3206. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  3207. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  3208. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  3209. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  3210. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  3211. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  3212. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  3213. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  3214. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  3215. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  3216. ArgNum = 4;
  3217. HasRC = true;
  3218. break;
  3219. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3220. case X86::BI__builtin_ia32_getmantss_round_mask:
  3221. ArgNum = 5;
  3222. HasRC = true;
  3223. break;
  3224. }
  3225. llvm::APSInt Result;
  3226. // We can't check the value of a dependent argument.
  3227. Expr *Arg = TheCall->getArg(ArgNum);
  3228. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3229. return false;
  3230. // Check constant-ness first.
  3231. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3232. return true;
  3233. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  3234. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  3235. // combined with ROUND_NO_EXC.
  3236. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  3237. Result == 8/*ROUND_NO_EXC*/ ||
  3238. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  3239. return false;
  3240. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
  3241. << Arg->getSourceRange();
  3242. }
  3243. // Check if the gather/scatter scale is legal.
  3244. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  3245. CallExpr *TheCall) {
  3246. unsigned ArgNum = 0;
  3247. switch (BuiltinID) {
  3248. default:
  3249. return false;
  3250. case X86::BI__builtin_ia32_gatherpfdpd:
  3251. case X86::BI__builtin_ia32_gatherpfdps:
  3252. case X86::BI__builtin_ia32_gatherpfqpd:
  3253. case X86::BI__builtin_ia32_gatherpfqps:
  3254. case X86::BI__builtin_ia32_scatterpfdpd:
  3255. case X86::BI__builtin_ia32_scatterpfdps:
  3256. case X86::BI__builtin_ia32_scatterpfqpd:
  3257. case X86::BI__builtin_ia32_scatterpfqps:
  3258. ArgNum = 3;
  3259. break;
  3260. case X86::BI__builtin_ia32_gatherd_pd:
  3261. case X86::BI__builtin_ia32_gatherd_pd256:
  3262. case X86::BI__builtin_ia32_gatherq_pd:
  3263. case X86::BI__builtin_ia32_gatherq_pd256:
  3264. case X86::BI__builtin_ia32_gatherd_ps:
  3265. case X86::BI__builtin_ia32_gatherd_ps256:
  3266. case X86::BI__builtin_ia32_gatherq_ps:
  3267. case X86::BI__builtin_ia32_gatherq_ps256:
  3268. case X86::BI__builtin_ia32_gatherd_q:
  3269. case X86::BI__builtin_ia32_gatherd_q256:
  3270. case X86::BI__builtin_ia32_gatherq_q:
  3271. case X86::BI__builtin_ia32_gatherq_q256:
  3272. case X86::BI__builtin_ia32_gatherd_d:
  3273. case X86::BI__builtin_ia32_gatherd_d256:
  3274. case X86::BI__builtin_ia32_gatherq_d:
  3275. case X86::BI__builtin_ia32_gatherq_d256:
  3276. case X86::BI__builtin_ia32_gather3div2df:
  3277. case X86::BI__builtin_ia32_gather3div2di:
  3278. case X86::BI__builtin_ia32_gather3div4df:
  3279. case X86::BI__builtin_ia32_gather3div4di:
  3280. case X86::BI__builtin_ia32_gather3div4sf:
  3281. case X86::BI__builtin_ia32_gather3div4si:
  3282. case X86::BI__builtin_ia32_gather3div8sf:
  3283. case X86::BI__builtin_ia32_gather3div8si:
  3284. case X86::BI__builtin_ia32_gather3siv2df:
  3285. case X86::BI__builtin_ia32_gather3siv2di:
  3286. case X86::BI__builtin_ia32_gather3siv4df:
  3287. case X86::BI__builtin_ia32_gather3siv4di:
  3288. case X86::BI__builtin_ia32_gather3siv4sf:
  3289. case X86::BI__builtin_ia32_gather3siv4si:
  3290. case X86::BI__builtin_ia32_gather3siv8sf:
  3291. case X86::BI__builtin_ia32_gather3siv8si:
  3292. case X86::BI__builtin_ia32_gathersiv8df:
  3293. case X86::BI__builtin_ia32_gathersiv16sf:
  3294. case X86::BI__builtin_ia32_gatherdiv8df:
  3295. case X86::BI__builtin_ia32_gatherdiv16sf:
  3296. case X86::BI__builtin_ia32_gathersiv8di:
  3297. case X86::BI__builtin_ia32_gathersiv16si:
  3298. case X86::BI__builtin_ia32_gatherdiv8di:
  3299. case X86::BI__builtin_ia32_gatherdiv16si:
  3300. case X86::BI__builtin_ia32_scatterdiv2df:
  3301. case X86::BI__builtin_ia32_scatterdiv2di:
  3302. case X86::BI__builtin_ia32_scatterdiv4df:
  3303. case X86::BI__builtin_ia32_scatterdiv4di:
  3304. case X86::BI__builtin_ia32_scatterdiv4sf:
  3305. case X86::BI__builtin_ia32_scatterdiv4si:
  3306. case X86::BI__builtin_ia32_scatterdiv8sf:
  3307. case X86::BI__builtin_ia32_scatterdiv8si:
  3308. case X86::BI__builtin_ia32_scattersiv2df:
  3309. case X86::BI__builtin_ia32_scattersiv2di:
  3310. case X86::BI__builtin_ia32_scattersiv4df:
  3311. case X86::BI__builtin_ia32_scattersiv4di:
  3312. case X86::BI__builtin_ia32_scattersiv4sf:
  3313. case X86::BI__builtin_ia32_scattersiv4si:
  3314. case X86::BI__builtin_ia32_scattersiv8sf:
  3315. case X86::BI__builtin_ia32_scattersiv8si:
  3316. case X86::BI__builtin_ia32_scattersiv8df:
  3317. case X86::BI__builtin_ia32_scattersiv16sf:
  3318. case X86::BI__builtin_ia32_scatterdiv8df:
  3319. case X86::BI__builtin_ia32_scatterdiv16sf:
  3320. case X86::BI__builtin_ia32_scattersiv8di:
  3321. case X86::BI__builtin_ia32_scattersiv16si:
  3322. case X86::BI__builtin_ia32_scatterdiv8di:
  3323. case X86::BI__builtin_ia32_scatterdiv16si:
  3324. ArgNum = 4;
  3325. break;
  3326. }
  3327. llvm::APSInt Result;
  3328. // We can't check the value of a dependent argument.
  3329. Expr *Arg = TheCall->getArg(ArgNum);
  3330. if (Arg->isTypeDependent() || Arg->isValueDependent())
  3331. return false;
  3332. // Check constant-ness first.
  3333. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  3334. return true;
  3335. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  3336. return false;
  3337. return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
  3338. << Arg->getSourceRange();
  3339. }
  3340. static bool isX86_32Builtin(unsigned BuiltinID) {
  3341. // These builtins only work on x86-32 targets.
  3342. switch (BuiltinID) {
  3343. case X86::BI__builtin_ia32_readeflags_u32:
  3344. case X86::BI__builtin_ia32_writeeflags_u32:
  3345. return true;
  3346. }
  3347. return false;
  3348. }
  3349. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  3350. if (BuiltinID == X86::BI__builtin_cpu_supports)
  3351. return SemaBuiltinCpuSupports(*this, TheCall);
  3352. if (BuiltinID == X86::BI__builtin_cpu_is)
  3353. return SemaBuiltinCpuIs(*this, TheCall);
  3354. // Check for 32-bit only builtins on a 64-bit target.
  3355. const llvm::Triple &TT = Context.getTargetInfo().getTriple();
  3356. if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
  3357. return Diag(TheCall->getCallee()->getBeginLoc(),
  3358. diag::err_32_bit_builtin_64_bit_tgt);
  3359. // If the intrinsic has rounding or SAE make sure its valid.
  3360. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  3361. return true;
  3362. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  3363. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  3364. return true;
  3365. // For intrinsics which take an immediate value as part of the instruction,
  3366. // range check them here.
  3367. int i = 0, l = 0, u = 0;
  3368. switch (BuiltinID) {
  3369. default:
  3370. return false;
  3371. case X86::BI__builtin_ia32_vec_ext_v2si:
  3372. case X86::BI__builtin_ia32_vec_ext_v2di:
  3373. case X86::BI__builtin_ia32_vextractf128_pd256:
  3374. case X86::BI__builtin_ia32_vextractf128_ps256:
  3375. case X86::BI__builtin_ia32_vextractf128_si256:
  3376. case X86::BI__builtin_ia32_extract128i256:
  3377. case X86::BI__builtin_ia32_extractf64x4_mask:
  3378. case X86::BI__builtin_ia32_extracti64x4_mask:
  3379. case X86::BI__builtin_ia32_extractf32x8_mask:
  3380. case X86::BI__builtin_ia32_extracti32x8_mask:
  3381. case X86::BI__builtin_ia32_extractf64x2_256_mask:
  3382. case X86::BI__builtin_ia32_extracti64x2_256_mask:
  3383. case X86::BI__builtin_ia32_extractf32x4_256_mask:
  3384. case X86::BI__builtin_ia32_extracti32x4_256_mask:
  3385. i = 1; l = 0; u = 1;
  3386. break;
  3387. case X86::BI__builtin_ia32_vec_set_v2di:
  3388. case X86::BI__builtin_ia32_vinsertf128_pd256:
  3389. case X86::BI__builtin_ia32_vinsertf128_ps256:
  3390. case X86::BI__builtin_ia32_vinsertf128_si256:
  3391. case X86::BI__builtin_ia32_insert128i256:
  3392. case X86::BI__builtin_ia32_insertf32x8:
  3393. case X86::BI__builtin_ia32_inserti32x8:
  3394. case X86::BI__builtin_ia32_insertf64x4:
  3395. case X86::BI__builtin_ia32_inserti64x4:
  3396. case X86::BI__builtin_ia32_insertf64x2_256:
  3397. case X86::BI__builtin_ia32_inserti64x2_256:
  3398. case X86::BI__builtin_ia32_insertf32x4_256:
  3399. case X86::BI__builtin_ia32_inserti32x4_256:
  3400. i = 2; l = 0; u = 1;
  3401. break;
  3402. case X86::BI__builtin_ia32_vpermilpd:
  3403. case X86::BI__builtin_ia32_vec_ext_v4hi:
  3404. case X86::BI__builtin_ia32_vec_ext_v4si:
  3405. case X86::BI__builtin_ia32_vec_ext_v4sf:
  3406. case X86::BI__builtin_ia32_vec_ext_v4di:
  3407. case X86::BI__builtin_ia32_extractf32x4_mask:
  3408. case X86::BI__builtin_ia32_extracti32x4_mask:
  3409. case X86::BI__builtin_ia32_extractf64x2_512_mask:
  3410. case X86::BI__builtin_ia32_extracti64x2_512_mask:
  3411. i = 1; l = 0; u = 3;
  3412. break;
  3413. case X86::BI_mm_prefetch:
  3414. case X86::BI__builtin_ia32_vec_ext_v8hi:
  3415. case X86::BI__builtin_ia32_vec_ext_v8si:
  3416. i = 1; l = 0; u = 7;
  3417. break;
  3418. case X86::BI__builtin_ia32_sha1rnds4:
  3419. case X86::BI__builtin_ia32_blendpd:
  3420. case X86::BI__builtin_ia32_shufpd:
  3421. case X86::BI__builtin_ia32_vec_set_v4hi:
  3422. case X86::BI__builtin_ia32_vec_set_v4si:
  3423. case X86::BI__builtin_ia32_vec_set_v4di:
  3424. case X86::BI__builtin_ia32_shuf_f32x4_256:
  3425. case X86::BI__builtin_ia32_shuf_f64x2_256:
  3426. case X86::BI__builtin_ia32_shuf_i32x4_256:
  3427. case X86::BI__builtin_ia32_shuf_i64x2_256:
  3428. case X86::BI__builtin_ia32_insertf64x2_512:
  3429. case X86::BI__builtin_ia32_inserti64x2_512:
  3430. case X86::BI__builtin_ia32_insertf32x4:
  3431. case X86::BI__builtin_ia32_inserti32x4:
  3432. i = 2; l = 0; u = 3;
  3433. break;
  3434. case X86::BI__builtin_ia32_vpermil2pd:
  3435. case X86::BI__builtin_ia32_vpermil2pd256:
  3436. case X86::BI__builtin_ia32_vpermil2ps:
  3437. case X86::BI__builtin_ia32_vpermil2ps256:
  3438. i = 3; l = 0; u = 3;
  3439. break;
  3440. case X86::BI__builtin_ia32_cmpb128_mask:
  3441. case X86::BI__builtin_ia32_cmpw128_mask:
  3442. case X86::BI__builtin_ia32_cmpd128_mask:
  3443. case X86::BI__builtin_ia32_cmpq128_mask:
  3444. case X86::BI__builtin_ia32_cmpb256_mask:
  3445. case X86::BI__builtin_ia32_cmpw256_mask:
  3446. case X86::BI__builtin_ia32_cmpd256_mask:
  3447. case X86::BI__builtin_ia32_cmpq256_mask:
  3448. case X86::BI__builtin_ia32_cmpb512_mask:
  3449. case X86::BI__builtin_ia32_cmpw512_mask:
  3450. case X86::BI__builtin_ia32_cmpd512_mask:
  3451. case X86::BI__builtin_ia32_cmpq512_mask:
  3452. case X86::BI__builtin_ia32_ucmpb128_mask:
  3453. case X86::BI__builtin_ia32_ucmpw128_mask:
  3454. case X86::BI__builtin_ia32_ucmpd128_mask:
  3455. case X86::BI__builtin_ia32_ucmpq128_mask:
  3456. case X86::BI__builtin_ia32_ucmpb256_mask:
  3457. case X86::BI__builtin_ia32_ucmpw256_mask:
  3458. case X86::BI__builtin_ia32_ucmpd256_mask:
  3459. case X86::BI__builtin_ia32_ucmpq256_mask:
  3460. case X86::BI__builtin_ia32_ucmpb512_mask:
  3461. case X86::BI__builtin_ia32_ucmpw512_mask:
  3462. case X86::BI__builtin_ia32_ucmpd512_mask:
  3463. case X86::BI__builtin_ia32_ucmpq512_mask:
  3464. case X86::BI__builtin_ia32_vpcomub:
  3465. case X86::BI__builtin_ia32_vpcomuw:
  3466. case X86::BI__builtin_ia32_vpcomud:
  3467. case X86::BI__builtin_ia32_vpcomuq:
  3468. case X86::BI__builtin_ia32_vpcomb:
  3469. case X86::BI__builtin_ia32_vpcomw:
  3470. case X86::BI__builtin_ia32_vpcomd:
  3471. case X86::BI__builtin_ia32_vpcomq:
  3472. case X86::BI__builtin_ia32_vec_set_v8hi:
  3473. case X86::BI__builtin_ia32_vec_set_v8si:
  3474. i = 2; l = 0; u = 7;
  3475. break;
  3476. case X86::BI__builtin_ia32_vpermilpd256:
  3477. case X86::BI__builtin_ia32_roundps:
  3478. case X86::BI__builtin_ia32_roundpd:
  3479. case X86::BI__builtin_ia32_roundps256:
  3480. case X86::BI__builtin_ia32_roundpd256:
  3481. case X86::BI__builtin_ia32_getmantpd128_mask:
  3482. case X86::BI__builtin_ia32_getmantpd256_mask:
  3483. case X86::BI__builtin_ia32_getmantps128_mask:
  3484. case X86::BI__builtin_ia32_getmantps256_mask:
  3485. case X86::BI__builtin_ia32_getmantpd512_mask:
  3486. case X86::BI__builtin_ia32_getmantps512_mask:
  3487. case X86::BI__builtin_ia32_vec_ext_v16qi:
  3488. case X86::BI__builtin_ia32_vec_ext_v16hi:
  3489. i = 1; l = 0; u = 15;
  3490. break;
  3491. case X86::BI__builtin_ia32_pblendd128:
  3492. case X86::BI__builtin_ia32_blendps:
  3493. case X86::BI__builtin_ia32_blendpd256:
  3494. case X86::BI__builtin_ia32_shufpd256:
  3495. case X86::BI__builtin_ia32_roundss:
  3496. case X86::BI__builtin_ia32_roundsd:
  3497. case X86::BI__builtin_ia32_rangepd128_mask:
  3498. case X86::BI__builtin_ia32_rangepd256_mask:
  3499. case X86::BI__builtin_ia32_rangepd512_mask:
  3500. case X86::BI__builtin_ia32_rangeps128_mask:
  3501. case X86::BI__builtin_ia32_rangeps256_mask:
  3502. case X86::BI__builtin_ia32_rangeps512_mask:
  3503. case X86::BI__builtin_ia32_getmantsd_round_mask:
  3504. case X86::BI__builtin_ia32_getmantss_round_mask:
  3505. case X86::BI__builtin_ia32_vec_set_v16qi:
  3506. case X86::BI__builtin_ia32_vec_set_v16hi:
  3507. i = 2; l = 0; u = 15;
  3508. break;
  3509. case X86::BI__builtin_ia32_vec_ext_v32qi:
  3510. i = 1; l = 0; u = 31;
  3511. break;
  3512. case X86::BI__builtin_ia32_cmpps:
  3513. case X86::BI__builtin_ia32_cmpss:
  3514. case X86::BI__builtin_ia32_cmppd:
  3515. case X86::BI__builtin_ia32_cmpsd:
  3516. case X86::BI__builtin_ia32_cmpps256:
  3517. case X86::BI__builtin_ia32_cmppd256:
  3518. case X86::BI__builtin_ia32_cmpps128_mask:
  3519. case X86::BI__builtin_ia32_cmppd128_mask:
  3520. case X86::BI__builtin_ia32_cmpps256_mask:
  3521. case X86::BI__builtin_ia32_cmppd256_mask:
  3522. case X86::BI__builtin_ia32_cmpps512_mask:
  3523. case X86::BI__builtin_ia32_cmppd512_mask:
  3524. case X86::BI__builtin_ia32_cmpsd_mask:
  3525. case X86::BI__builtin_ia32_cmpss_mask:
  3526. case X86::BI__builtin_ia32_vec_set_v32qi:
  3527. i = 2; l = 0; u = 31;
  3528. break;
  3529. case X86::BI__builtin_ia32_permdf256:
  3530. case X86::BI__builtin_ia32_permdi256:
  3531. case X86::BI__builtin_ia32_permdf512:
  3532. case X86::BI__builtin_ia32_permdi512:
  3533. case X86::BI__builtin_ia32_vpermilps:
  3534. case X86::BI__builtin_ia32_vpermilps256:
  3535. case X86::BI__builtin_ia32_vpermilpd512:
  3536. case X86::BI__builtin_ia32_vpermilps512:
  3537. case X86::BI__builtin_ia32_pshufd:
  3538. case X86::BI__builtin_ia32_pshufd256:
  3539. case X86::BI__builtin_ia32_pshufd512:
  3540. case X86::BI__builtin_ia32_pshufhw:
  3541. case X86::BI__builtin_ia32_pshufhw256:
  3542. case X86::BI__builtin_ia32_pshufhw512:
  3543. case X86::BI__builtin_ia32_pshuflw:
  3544. case X86::BI__builtin_ia32_pshuflw256:
  3545. case X86::BI__builtin_ia32_pshuflw512:
  3546. case X86::BI__builtin_ia32_vcvtps2ph:
  3547. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  3548. case X86::BI__builtin_ia32_vcvtps2ph256:
  3549. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  3550. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  3551. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  3552. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  3553. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  3554. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  3555. case X86::BI__builtin_ia32_rndscaleps_mask:
  3556. case X86::BI__builtin_ia32_rndscalepd_mask:
  3557. case X86::BI__builtin_ia32_reducepd128_mask:
  3558. case X86::BI__builtin_ia32_reducepd256_mask:
  3559. case X86::BI__builtin_ia32_reducepd512_mask:
  3560. case X86::BI__builtin_ia32_reduceps128_mask:
  3561. case X86::BI__builtin_ia32_reduceps256_mask:
  3562. case X86::BI__builtin_ia32_reduceps512_mask:
  3563. case X86::BI__builtin_ia32_prold512:
  3564. case X86::BI__builtin_ia32_prolq512:
  3565. case X86::BI__builtin_ia32_prold128:
  3566. case X86::BI__builtin_ia32_prold256:
  3567. case X86::BI__builtin_ia32_prolq128:
  3568. case X86::BI__builtin_ia32_prolq256:
  3569. case X86::BI__builtin_ia32_prord512:
  3570. case X86::BI__builtin_ia32_prorq512:
  3571. case X86::BI__builtin_ia32_prord128:
  3572. case X86::BI__builtin_ia32_prord256:
  3573. case X86::BI__builtin_ia32_prorq128:
  3574. case X86::BI__builtin_ia32_prorq256:
  3575. case X86::BI__builtin_ia32_fpclasspd128_mask:
  3576. case X86::BI__builtin_ia32_fpclasspd256_mask:
  3577. case X86::BI__builtin_ia32_fpclassps128_mask:
  3578. case X86::BI__builtin_ia32_fpclassps256_mask:
  3579. case X86::BI__builtin_ia32_fpclassps512_mask:
  3580. case X86::BI__builtin_ia32_fpclasspd512_mask:
  3581. case X86::BI__builtin_ia32_fpclasssd_mask:
  3582. case X86::BI__builtin_ia32_fpclassss_mask:
  3583. case X86::BI__builtin_ia32_pslldqi128_byteshift:
  3584. case X86::BI__builtin_ia32_pslldqi256_byteshift:
  3585. case X86::BI__builtin_ia32_pslldqi512_byteshift:
  3586. case X86::BI__builtin_ia32_psrldqi128_byteshift:
  3587. case X86::BI__builtin_ia32_psrldqi256_byteshift:
  3588. case X86::BI__builtin_ia32_psrldqi512_byteshift:
  3589. case X86::BI__builtin_ia32_kshiftliqi:
  3590. case X86::BI__builtin_ia32_kshiftlihi:
  3591. case X86::BI__builtin_ia32_kshiftlisi:
  3592. case X86::BI__builtin_ia32_kshiftlidi:
  3593. case X86::BI__builtin_ia32_kshiftriqi:
  3594. case X86::BI__builtin_ia32_kshiftrihi:
  3595. case X86::BI__builtin_ia32_kshiftrisi:
  3596. case X86::BI__builtin_ia32_kshiftridi:
  3597. i = 1; l = 0; u = 255;
  3598. break;
  3599. case X86::BI__builtin_ia32_vperm2f128_pd256:
  3600. case X86::BI__builtin_ia32_vperm2f128_ps256:
  3601. case X86::BI__builtin_ia32_vperm2f128_si256:
  3602. case X86::BI__builtin_ia32_permti256:
  3603. case X86::BI__builtin_ia32_pblendw128:
  3604. case X86::BI__builtin_ia32_pblendw256:
  3605. case X86::BI__builtin_ia32_blendps256:
  3606. case X86::BI__builtin_ia32_pblendd256:
  3607. case X86::BI__builtin_ia32_palignr128:
  3608. case X86::BI__builtin_ia32_palignr256:
  3609. case X86::BI__builtin_ia32_palignr512:
  3610. case X86::BI__builtin_ia32_alignq512:
  3611. case X86::BI__builtin_ia32_alignd512:
  3612. case X86::BI__builtin_ia32_alignd128:
  3613. case X86::BI__builtin_ia32_alignd256:
  3614. case X86::BI__builtin_ia32_alignq128:
  3615. case X86::BI__builtin_ia32_alignq256:
  3616. case X86::BI__builtin_ia32_vcomisd:
  3617. case X86::BI__builtin_ia32_vcomiss:
  3618. case X86::BI__builtin_ia32_shuf_f32x4:
  3619. case X86::BI__builtin_ia32_shuf_f64x2:
  3620. case X86::BI__builtin_ia32_shuf_i32x4:
  3621. case X86::BI__builtin_ia32_shuf_i64x2:
  3622. case X86::BI__builtin_ia32_shufpd512:
  3623. case X86::BI__builtin_ia32_shufps:
  3624. case X86::BI__builtin_ia32_shufps256:
  3625. case X86::BI__builtin_ia32_shufps512:
  3626. case X86::BI__builtin_ia32_dbpsadbw128:
  3627. case X86::BI__builtin_ia32_dbpsadbw256:
  3628. case X86::BI__builtin_ia32_dbpsadbw512:
  3629. case X86::BI__builtin_ia32_vpshldd128:
  3630. case X86::BI__builtin_ia32_vpshldd256:
  3631. case X86::BI__builtin_ia32_vpshldd512:
  3632. case X86::BI__builtin_ia32_vpshldq128:
  3633. case X86::BI__builtin_ia32_vpshldq256:
  3634. case X86::BI__builtin_ia32_vpshldq512:
  3635. case X86::BI__builtin_ia32_vpshldw128:
  3636. case X86::BI__builtin_ia32_vpshldw256:
  3637. case X86::BI__builtin_ia32_vpshldw512:
  3638. case X86::BI__builtin_ia32_vpshrdd128:
  3639. case X86::BI__builtin_ia32_vpshrdd256:
  3640. case X86::BI__builtin_ia32_vpshrdd512:
  3641. case X86::BI__builtin_ia32_vpshrdq128:
  3642. case X86::BI__builtin_ia32_vpshrdq256:
  3643. case X86::BI__builtin_ia32_vpshrdq512:
  3644. case X86::BI__builtin_ia32_vpshrdw128:
  3645. case X86::BI__builtin_ia32_vpshrdw256:
  3646. case X86::BI__builtin_ia32_vpshrdw512:
  3647. i = 2; l = 0; u = 255;
  3648. break;
  3649. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  3650. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  3651. case X86::BI__builtin_ia32_fixupimmps512_mask:
  3652. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  3653. case X86::BI__builtin_ia32_fixupimmsd_mask:
  3654. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  3655. case X86::BI__builtin_ia32_fixupimmss_mask:
  3656. case X86::BI__builtin_ia32_fixupimmss_maskz:
  3657. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  3658. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  3659. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  3660. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  3661. case X86::BI__builtin_ia32_fixupimmps128_mask:
  3662. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  3663. case X86::BI__builtin_ia32_fixupimmps256_mask:
  3664. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  3665. case X86::BI__builtin_ia32_pternlogd512_mask:
  3666. case X86::BI__builtin_ia32_pternlogd512_maskz:
  3667. case X86::BI__builtin_ia32_pternlogq512_mask:
  3668. case X86::BI__builtin_ia32_pternlogq512_maskz:
  3669. case X86::BI__builtin_ia32_pternlogd128_mask:
  3670. case X86::BI__builtin_ia32_pternlogd128_maskz:
  3671. case X86::BI__builtin_ia32_pternlogd256_mask:
  3672. case X86::BI__builtin_ia32_pternlogd256_maskz:
  3673. case X86::BI__builtin_ia32_pternlogq128_mask:
  3674. case X86::BI__builtin_ia32_pternlogq128_maskz:
  3675. case X86::BI__builtin_ia32_pternlogq256_mask:
  3676. case X86::BI__builtin_ia32_pternlogq256_maskz:
  3677. i = 3; l = 0; u = 255;
  3678. break;
  3679. case X86::BI__builtin_ia32_gatherpfdpd:
  3680. case X86::BI__builtin_ia32_gatherpfdps:
  3681. case X86::BI__builtin_ia32_gatherpfqpd:
  3682. case X86::BI__builtin_ia32_gatherpfqps:
  3683. case X86::BI__builtin_ia32_scatterpfdpd:
  3684. case X86::BI__builtin_ia32_scatterpfdps:
  3685. case X86::BI__builtin_ia32_scatterpfqpd:
  3686. case X86::BI__builtin_ia32_scatterpfqps:
  3687. i = 4; l = 2; u = 3;
  3688. break;
  3689. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  3690. case X86::BI__builtin_ia32_rndscaless_round_mask:
  3691. i = 4; l = 0; u = 255;
  3692. break;
  3693. }
  3694. // Note that we don't force a hard error on the range check here, allowing
  3695. // template-generated or macro-generated dead code to potentially have out-of-
  3696. // range values. These need to code generate, but don't need to necessarily
  3697. // make any sense. We use a warning that defaults to an error.
  3698. return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
  3699. }
  3700. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  3701. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  3702. /// Returns true when the format fits the function and the FormatStringInfo has
  3703. /// been populated.
  3704. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  3705. FormatStringInfo *FSI) {
  3706. FSI->HasVAListArg = Format->getFirstArg() == 0;
  3707. FSI->FormatIdx = Format->getFormatIdx() - 1;
  3708. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  3709. // The way the format attribute works in GCC, the implicit this argument
  3710. // of member functions is counted. However, it doesn't appear in our own
  3711. // lists, so decrement format_idx in that case.
  3712. if (IsCXXMember) {
  3713. if(FSI->FormatIdx == 0)
  3714. return false;
  3715. --FSI->FormatIdx;
  3716. if (FSI->FirstDataArg != 0)
  3717. --FSI->FirstDataArg;
  3718. }
  3719. return true;
  3720. }
  3721. /// Checks if a the given expression evaluates to null.
  3722. ///
  3723. /// Returns true if the value evaluates to null.
  3724. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  3725. // If the expression has non-null type, it doesn't evaluate to null.
  3726. if (auto nullability
  3727. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  3728. if (*nullability == NullabilityKind::NonNull)
  3729. return false;
  3730. }
  3731. // As a special case, transparent unions initialized with zero are
  3732. // considered null for the purposes of the nonnull attribute.
  3733. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  3734. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3735. if (const CompoundLiteralExpr *CLE =
  3736. dyn_cast<CompoundLiteralExpr>(Expr))
  3737. if (const InitListExpr *ILE =
  3738. dyn_cast<InitListExpr>(CLE->getInitializer()))
  3739. Expr = ILE->getInit(0);
  3740. }
  3741. bool Result;
  3742. return (!Expr->isValueDependent() &&
  3743. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  3744. !Result);
  3745. }
  3746. static void CheckNonNullArgument(Sema &S,
  3747. const Expr *ArgExpr,
  3748. SourceLocation CallSiteLoc) {
  3749. if (CheckNonNullExpr(S, ArgExpr))
  3750. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  3751. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  3752. }
  3753. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  3754. FormatStringInfo FSI;
  3755. if ((GetFormatStringType(Format) == FST_NSString) &&
  3756. getFormatStringInfo(Format, false, &FSI)) {
  3757. Idx = FSI.FormatIdx;
  3758. return true;
  3759. }
  3760. return false;
  3761. }
  3762. /// Diagnose use of %s directive in an NSString which is being passed
  3763. /// as formatting string to formatting method.
  3764. static void
  3765. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  3766. const NamedDecl *FDecl,
  3767. Expr **Args,
  3768. unsigned NumArgs) {
  3769. unsigned Idx = 0;
  3770. bool Format = false;
  3771. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  3772. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  3773. Idx = 2;
  3774. Format = true;
  3775. }
  3776. else
  3777. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3778. if (S.GetFormatNSStringIdx(I, Idx)) {
  3779. Format = true;
  3780. break;
  3781. }
  3782. }
  3783. if (!Format || NumArgs <= Idx)
  3784. return;
  3785. const Expr *FormatExpr = Args[Idx];
  3786. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  3787. FormatExpr = CSCE->getSubExpr();
  3788. const StringLiteral *FormatString;
  3789. if (const ObjCStringLiteral *OSL =
  3790. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  3791. FormatString = OSL->getString();
  3792. else
  3793. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  3794. if (!FormatString)
  3795. return;
  3796. if (S.FormatStringHasSArg(FormatString)) {
  3797. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  3798. << "%s" << 1 << 1;
  3799. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  3800. << FDecl->getDeclName();
  3801. }
  3802. }
  3803. /// Determine whether the given type has a non-null nullability annotation.
  3804. static bool isNonNullType(ASTContext &ctx, QualType type) {
  3805. if (auto nullability = type->getNullability(ctx))
  3806. return *nullability == NullabilityKind::NonNull;
  3807. return false;
  3808. }
  3809. static void CheckNonNullArguments(Sema &S,
  3810. const NamedDecl *FDecl,
  3811. const FunctionProtoType *Proto,
  3812. ArrayRef<const Expr *> Args,
  3813. SourceLocation CallSiteLoc) {
  3814. assert((FDecl || Proto) && "Need a function declaration or prototype");
  3815. // Check the attributes attached to the method/function itself.
  3816. llvm::SmallBitVector NonNullArgs;
  3817. if (FDecl) {
  3818. // Handle the nonnull attribute on the function/method declaration itself.
  3819. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  3820. if (!NonNull->args_size()) {
  3821. // Easy case: all pointer arguments are nonnull.
  3822. for (const auto *Arg : Args)
  3823. if (S.isValidPointerAttrType(Arg->getType()))
  3824. CheckNonNullArgument(S, Arg, CallSiteLoc);
  3825. return;
  3826. }
  3827. for (const ParamIdx &Idx : NonNull->args()) {
  3828. unsigned IdxAST = Idx.getASTIndex();
  3829. if (IdxAST >= Args.size())
  3830. continue;
  3831. if (NonNullArgs.empty())
  3832. NonNullArgs.resize(Args.size());
  3833. NonNullArgs.set(IdxAST);
  3834. }
  3835. }
  3836. }
  3837. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  3838. // Handle the nonnull attribute on the parameters of the
  3839. // function/method.
  3840. ArrayRef<ParmVarDecl*> parms;
  3841. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  3842. parms = FD->parameters();
  3843. else
  3844. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  3845. unsigned ParamIndex = 0;
  3846. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  3847. I != E; ++I, ++ParamIndex) {
  3848. const ParmVarDecl *PVD = *I;
  3849. if (PVD->hasAttr<NonNullAttr>() ||
  3850. isNonNullType(S.Context, PVD->getType())) {
  3851. if (NonNullArgs.empty())
  3852. NonNullArgs.resize(Args.size());
  3853. NonNullArgs.set(ParamIndex);
  3854. }
  3855. }
  3856. } else {
  3857. // If we have a non-function, non-method declaration but no
  3858. // function prototype, try to dig out the function prototype.
  3859. if (!Proto) {
  3860. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  3861. QualType type = VD->getType().getNonReferenceType();
  3862. if (auto pointerType = type->getAs<PointerType>())
  3863. type = pointerType->getPointeeType();
  3864. else if (auto blockType = type->getAs<BlockPointerType>())
  3865. type = blockType->getPointeeType();
  3866. // FIXME: data member pointers?
  3867. // Dig out the function prototype, if there is one.
  3868. Proto = type->getAs<FunctionProtoType>();
  3869. }
  3870. }
  3871. // Fill in non-null argument information from the nullability
  3872. // information on the parameter types (if we have them).
  3873. if (Proto) {
  3874. unsigned Index = 0;
  3875. for (auto paramType : Proto->getParamTypes()) {
  3876. if (isNonNullType(S.Context, paramType)) {
  3877. if (NonNullArgs.empty())
  3878. NonNullArgs.resize(Args.size());
  3879. NonNullArgs.set(Index);
  3880. }
  3881. ++Index;
  3882. }
  3883. }
  3884. }
  3885. // Check for non-null arguments.
  3886. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  3887. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  3888. if (NonNullArgs[ArgIndex])
  3889. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  3890. }
  3891. }
  3892. /// Handles the checks for format strings, non-POD arguments to vararg
  3893. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  3894. /// attributes.
  3895. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  3896. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  3897. bool IsMemberFunction, SourceLocation Loc,
  3898. SourceRange Range, VariadicCallType CallType) {
  3899. // FIXME: We should check as much as we can in the template definition.
  3900. if (CurContext->isDependentContext())
  3901. return;
  3902. // Printf and scanf checking.
  3903. llvm::SmallBitVector CheckedVarArgs;
  3904. if (FDecl) {
  3905. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  3906. // Only create vector if there are format attributes.
  3907. CheckedVarArgs.resize(Args.size());
  3908. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  3909. CheckedVarArgs);
  3910. }
  3911. }
  3912. // Refuse POD arguments that weren't caught by the format string
  3913. // checks above.
  3914. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  3915. if (CallType != VariadicDoesNotApply &&
  3916. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  3917. unsigned NumParams = Proto ? Proto->getNumParams()
  3918. : FDecl && isa<FunctionDecl>(FDecl)
  3919. ? cast<FunctionDecl>(FDecl)->getNumParams()
  3920. : FDecl && isa<ObjCMethodDecl>(FDecl)
  3921. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  3922. : 0;
  3923. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  3924. // Args[ArgIdx] can be null in malformed code.
  3925. if (const Expr *Arg = Args[ArgIdx]) {
  3926. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  3927. checkVariadicArgument(Arg, CallType);
  3928. }
  3929. }
  3930. }
  3931. if (FDecl || Proto) {
  3932. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  3933. // Type safety checking.
  3934. if (FDecl) {
  3935. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  3936. CheckArgumentWithTypeTag(I, Args, Loc);
  3937. }
  3938. }
  3939. if (FD)
  3940. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  3941. }
  3942. /// CheckConstructorCall - Check a constructor call for correctness and safety
  3943. /// properties not enforced by the C type system.
  3944. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  3945. ArrayRef<const Expr *> Args,
  3946. const FunctionProtoType *Proto,
  3947. SourceLocation Loc) {
  3948. VariadicCallType CallType =
  3949. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  3950. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  3951. Loc, SourceRange(), CallType);
  3952. }
  3953. /// CheckFunctionCall - Check a direct function call for various correctness
  3954. /// and safety properties not strictly enforced by the C type system.
  3955. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  3956. const FunctionProtoType *Proto) {
  3957. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  3958. isa<CXXMethodDecl>(FDecl);
  3959. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  3960. IsMemberOperatorCall;
  3961. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  3962. TheCall->getCallee());
  3963. Expr** Args = TheCall->getArgs();
  3964. unsigned NumArgs = TheCall->getNumArgs();
  3965. Expr *ImplicitThis = nullptr;
  3966. if (IsMemberOperatorCall) {
  3967. // If this is a call to a member operator, hide the first argument
  3968. // from checkCall.
  3969. // FIXME: Our choice of AST representation here is less than ideal.
  3970. ImplicitThis = Args[0];
  3971. ++Args;
  3972. --NumArgs;
  3973. } else if (IsMemberFunction)
  3974. ImplicitThis =
  3975. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  3976. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  3977. IsMemberFunction, TheCall->getRParenLoc(),
  3978. TheCall->getCallee()->getSourceRange(), CallType);
  3979. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  3980. // None of the checks below are needed for functions that don't have
  3981. // simple names (e.g., C++ conversion functions).
  3982. if (!FnInfo)
  3983. return false;
  3984. CheckAbsoluteValueFunction(TheCall, FDecl);
  3985. CheckMaxUnsignedZero(TheCall, FDecl);
  3986. if (getLangOpts().ObjC)
  3987. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  3988. unsigned CMId = FDecl->getMemoryFunctionKind();
  3989. if (CMId == 0)
  3990. return false;
  3991. // Handle memory setting and copying functions.
  3992. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  3993. CheckStrlcpycatArguments(TheCall, FnInfo);
  3994. else if (CMId == Builtin::BIstrncat)
  3995. CheckStrncatArguments(TheCall, FnInfo);
  3996. else
  3997. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  3998. return false;
  3999. }
  4000. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  4001. ArrayRef<const Expr *> Args) {
  4002. VariadicCallType CallType =
  4003. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  4004. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  4005. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  4006. CallType);
  4007. return false;
  4008. }
  4009. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  4010. const FunctionProtoType *Proto) {
  4011. QualType Ty;
  4012. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  4013. Ty = V->getType().getNonReferenceType();
  4014. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  4015. Ty = F->getType().getNonReferenceType();
  4016. else
  4017. return false;
  4018. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  4019. !Ty->isFunctionProtoType())
  4020. return false;
  4021. VariadicCallType CallType;
  4022. if (!Proto || !Proto->isVariadic()) {
  4023. CallType = VariadicDoesNotApply;
  4024. } else if (Ty->isBlockPointerType()) {
  4025. CallType = VariadicBlock;
  4026. } else { // Ty->isFunctionPointerType()
  4027. CallType = VariadicFunction;
  4028. }
  4029. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  4030. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4031. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4032. TheCall->getCallee()->getSourceRange(), CallType);
  4033. return false;
  4034. }
  4035. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  4036. /// such as function pointers returned from functions.
  4037. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  4038. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  4039. TheCall->getCallee());
  4040. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  4041. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  4042. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  4043. TheCall->getCallee()->getSourceRange(), CallType);
  4044. return false;
  4045. }
  4046. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  4047. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  4048. return false;
  4049. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  4050. switch (Op) {
  4051. case AtomicExpr::AO__c11_atomic_init:
  4052. case AtomicExpr::AO__opencl_atomic_init:
  4053. llvm_unreachable("There is no ordering argument for an init");
  4054. case AtomicExpr::AO__c11_atomic_load:
  4055. case AtomicExpr::AO__opencl_atomic_load:
  4056. case AtomicExpr::AO__atomic_load_n:
  4057. case AtomicExpr::AO__atomic_load:
  4058. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  4059. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4060. case AtomicExpr::AO__c11_atomic_store:
  4061. case AtomicExpr::AO__opencl_atomic_store:
  4062. case AtomicExpr::AO__atomic_store:
  4063. case AtomicExpr::AO__atomic_store_n:
  4064. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  4065. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  4066. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  4067. default:
  4068. return true;
  4069. }
  4070. }
  4071. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  4072. AtomicExpr::AtomicOp Op) {
  4073. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  4074. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4075. // All the non-OpenCL operations take one of the following forms.
  4076. // The OpenCL operations take the __c11 forms with one extra argument for
  4077. // synchronization scope.
  4078. enum {
  4079. // C __c11_atomic_init(A *, C)
  4080. Init,
  4081. // C __c11_atomic_load(A *, int)
  4082. Load,
  4083. // void __atomic_load(A *, CP, int)
  4084. LoadCopy,
  4085. // void __atomic_store(A *, CP, int)
  4086. Copy,
  4087. // C __c11_atomic_add(A *, M, int)
  4088. Arithmetic,
  4089. // C __atomic_exchange_n(A *, CP, int)
  4090. Xchg,
  4091. // void __atomic_exchange(A *, C *, CP, int)
  4092. GNUXchg,
  4093. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  4094. C11CmpXchg,
  4095. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  4096. GNUCmpXchg
  4097. } Form = Init;
  4098. const unsigned NumForm = GNUCmpXchg + 1;
  4099. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  4100. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  4101. // where:
  4102. // C is an appropriate type,
  4103. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  4104. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  4105. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  4106. // the int parameters are for orderings.
  4107. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  4108. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  4109. "need to update code for modified forms");
  4110. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  4111. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  4112. AtomicExpr::AO__atomic_load,
  4113. "need to update code for modified C11 atomics");
  4114. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  4115. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  4116. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  4117. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  4118. IsOpenCL;
  4119. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  4120. Op == AtomicExpr::AO__atomic_store_n ||
  4121. Op == AtomicExpr::AO__atomic_exchange_n ||
  4122. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  4123. bool IsAddSub = false;
  4124. bool IsMinMax = false;
  4125. switch (Op) {
  4126. case AtomicExpr::AO__c11_atomic_init:
  4127. case AtomicExpr::AO__opencl_atomic_init:
  4128. Form = Init;
  4129. break;
  4130. case AtomicExpr::AO__c11_atomic_load:
  4131. case AtomicExpr::AO__opencl_atomic_load:
  4132. case AtomicExpr::AO__atomic_load_n:
  4133. Form = Load;
  4134. break;
  4135. case AtomicExpr::AO__atomic_load:
  4136. Form = LoadCopy;
  4137. break;
  4138. case AtomicExpr::AO__c11_atomic_store:
  4139. case AtomicExpr::AO__opencl_atomic_store:
  4140. case AtomicExpr::AO__atomic_store:
  4141. case AtomicExpr::AO__atomic_store_n:
  4142. Form = Copy;
  4143. break;
  4144. case AtomicExpr::AO__c11_atomic_fetch_add:
  4145. case AtomicExpr::AO__c11_atomic_fetch_sub:
  4146. case AtomicExpr::AO__opencl_atomic_fetch_add:
  4147. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  4148. case AtomicExpr::AO__opencl_atomic_fetch_min:
  4149. case AtomicExpr::AO__opencl_atomic_fetch_max:
  4150. case AtomicExpr::AO__atomic_fetch_add:
  4151. case AtomicExpr::AO__atomic_fetch_sub:
  4152. case AtomicExpr::AO__atomic_add_fetch:
  4153. case AtomicExpr::AO__atomic_sub_fetch:
  4154. IsAddSub = true;
  4155. LLVM_FALLTHROUGH;
  4156. case AtomicExpr::AO__c11_atomic_fetch_and:
  4157. case AtomicExpr::AO__c11_atomic_fetch_or:
  4158. case AtomicExpr::AO__c11_atomic_fetch_xor:
  4159. case AtomicExpr::AO__opencl_atomic_fetch_and:
  4160. case AtomicExpr::AO__opencl_atomic_fetch_or:
  4161. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  4162. case AtomicExpr::AO__atomic_fetch_and:
  4163. case AtomicExpr::AO__atomic_fetch_or:
  4164. case AtomicExpr::AO__atomic_fetch_xor:
  4165. case AtomicExpr::AO__atomic_fetch_nand:
  4166. case AtomicExpr::AO__atomic_and_fetch:
  4167. case AtomicExpr::AO__atomic_or_fetch:
  4168. case AtomicExpr::AO__atomic_xor_fetch:
  4169. case AtomicExpr::AO__atomic_nand_fetch:
  4170. Form = Arithmetic;
  4171. break;
  4172. case AtomicExpr::AO__atomic_fetch_min:
  4173. case AtomicExpr::AO__atomic_fetch_max:
  4174. IsMinMax = true;
  4175. Form = Arithmetic;
  4176. break;
  4177. case AtomicExpr::AO__c11_atomic_exchange:
  4178. case AtomicExpr::AO__opencl_atomic_exchange:
  4179. case AtomicExpr::AO__atomic_exchange_n:
  4180. Form = Xchg;
  4181. break;
  4182. case AtomicExpr::AO__atomic_exchange:
  4183. Form = GNUXchg;
  4184. break;
  4185. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  4186. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  4187. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  4188. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  4189. Form = C11CmpXchg;
  4190. break;
  4191. case AtomicExpr::AO__atomic_compare_exchange:
  4192. case AtomicExpr::AO__atomic_compare_exchange_n:
  4193. Form = GNUCmpXchg;
  4194. break;
  4195. }
  4196. unsigned AdjustedNumArgs = NumArgs[Form];
  4197. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  4198. ++AdjustedNumArgs;
  4199. // Check we have the right number of arguments.
  4200. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  4201. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  4202. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4203. << TheCall->getCallee()->getSourceRange();
  4204. return ExprError();
  4205. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  4206. Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
  4207. diag::err_typecheck_call_too_many_args)
  4208. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  4209. << TheCall->getCallee()->getSourceRange();
  4210. return ExprError();
  4211. }
  4212. // Inspect the first argument of the atomic operation.
  4213. Expr *Ptr = TheCall->getArg(0);
  4214. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  4215. if (ConvertedPtr.isInvalid())
  4216. return ExprError();
  4217. Ptr = ConvertedPtr.get();
  4218. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  4219. if (!pointerType) {
  4220. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4221. << Ptr->getType() << Ptr->getSourceRange();
  4222. return ExprError();
  4223. }
  4224. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  4225. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  4226. QualType ValType = AtomTy; // 'C'
  4227. if (IsC11) {
  4228. if (!AtomTy->isAtomicType()) {
  4229. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
  4230. << Ptr->getType() << Ptr->getSourceRange();
  4231. return ExprError();
  4232. }
  4233. if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
  4234. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  4235. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
  4236. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  4237. << Ptr->getSourceRange();
  4238. return ExprError();
  4239. }
  4240. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  4241. } else if (Form != Load && Form != LoadCopy) {
  4242. if (ValType.isConstQualified()) {
  4243. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
  4244. << Ptr->getType() << Ptr->getSourceRange();
  4245. return ExprError();
  4246. }
  4247. }
  4248. // For an arithmetic operation, the implied arithmetic must be well-formed.
  4249. if (Form == Arithmetic) {
  4250. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  4251. if (IsAddSub && !ValType->isIntegerType()
  4252. && !ValType->isPointerType()) {
  4253. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4254. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4255. return ExprError();
  4256. }
  4257. if (IsMinMax) {
  4258. const BuiltinType *BT = ValType->getAs<BuiltinType>();
  4259. if (!BT || (BT->getKind() != BuiltinType::Int &&
  4260. BT->getKind() != BuiltinType::UInt)) {
  4261. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
  4262. return ExprError();
  4263. }
  4264. }
  4265. if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
  4266. Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
  4267. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4268. return ExprError();
  4269. }
  4270. if (IsC11 && ValType->isPointerType() &&
  4271. RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
  4272. diag::err_incomplete_type)) {
  4273. return ExprError();
  4274. }
  4275. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  4276. // For __atomic_*_n operations, the value type must be a scalar integral or
  4277. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  4278. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  4279. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  4280. return ExprError();
  4281. }
  4282. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  4283. !AtomTy->isScalarType()) {
  4284. // For GNU atomics, require a trivially-copyable type. This is not part of
  4285. // the GNU atomics specification, but we enforce it for sanity.
  4286. Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
  4287. << Ptr->getType() << Ptr->getSourceRange();
  4288. return ExprError();
  4289. }
  4290. switch (ValType.getObjCLifetime()) {
  4291. case Qualifiers::OCL_None:
  4292. case Qualifiers::OCL_ExplicitNone:
  4293. // okay
  4294. break;
  4295. case Qualifiers::OCL_Weak:
  4296. case Qualifiers::OCL_Strong:
  4297. case Qualifiers::OCL_Autoreleasing:
  4298. // FIXME: Can this happen? By this point, ValType should be known
  4299. // to be trivially copyable.
  4300. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4301. << ValType << Ptr->getSourceRange();
  4302. return ExprError();
  4303. }
  4304. // All atomic operations have an overload which takes a pointer to a volatile
  4305. // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
  4306. // into the result or the other operands. Similarly atomic_load takes a
  4307. // pointer to a const 'A'.
  4308. ValType.removeLocalVolatile();
  4309. ValType.removeLocalConst();
  4310. QualType ResultType = ValType;
  4311. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  4312. Form == Init)
  4313. ResultType = Context.VoidTy;
  4314. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  4315. ResultType = Context.BoolTy;
  4316. // The type of a parameter passed 'by value'. In the GNU atomics, such
  4317. // arguments are actually passed as pointers.
  4318. QualType ByValType = ValType; // 'CP'
  4319. bool IsPassedByAddress = false;
  4320. if (!IsC11 && !IsN) {
  4321. ByValType = Ptr->getType();
  4322. IsPassedByAddress = true;
  4323. }
  4324. // The first argument's non-CV pointer type is used to deduce the type of
  4325. // subsequent arguments, except for:
  4326. // - weak flag (always converted to bool)
  4327. // - memory order (always converted to int)
  4328. // - scope (always converted to int)
  4329. for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
  4330. QualType Ty;
  4331. if (i < NumVals[Form] + 1) {
  4332. switch (i) {
  4333. case 0:
  4334. // The first argument is always a pointer. It has a fixed type.
  4335. // It is always dereferenced, a nullptr is undefined.
  4336. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4337. // Nothing else to do: we already know all we want about this pointer.
  4338. continue;
  4339. case 1:
  4340. // The second argument is the non-atomic operand. For arithmetic, this
  4341. // is always passed by value, and for a compare_exchange it is always
  4342. // passed by address. For the rest, GNU uses by-address and C11 uses
  4343. // by-value.
  4344. assert(Form != Load);
  4345. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  4346. Ty = ValType;
  4347. else if (Form == Copy || Form == Xchg) {
  4348. if (IsPassedByAddress)
  4349. // The value pointer is always dereferenced, a nullptr is undefined.
  4350. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4351. Ty = ByValType;
  4352. } else if (Form == Arithmetic)
  4353. Ty = Context.getPointerDiffType();
  4354. else {
  4355. Expr *ValArg = TheCall->getArg(i);
  4356. // The value pointer is always dereferenced, a nullptr is undefined.
  4357. CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
  4358. LangAS AS = LangAS::Default;
  4359. // Keep address space of non-atomic pointer type.
  4360. if (const PointerType *PtrTy =
  4361. ValArg->getType()->getAs<PointerType>()) {
  4362. AS = PtrTy->getPointeeType().getAddressSpace();
  4363. }
  4364. Ty = Context.getPointerType(
  4365. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  4366. }
  4367. break;
  4368. case 2:
  4369. // The third argument to compare_exchange / GNU exchange is the desired
  4370. // value, either by-value (for the C11 and *_n variant) or as a pointer.
  4371. if (IsPassedByAddress)
  4372. CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
  4373. Ty = ByValType;
  4374. break;
  4375. case 3:
  4376. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  4377. Ty = Context.BoolTy;
  4378. break;
  4379. }
  4380. } else {
  4381. // The order(s) and scope are always converted to int.
  4382. Ty = Context.IntTy;
  4383. }
  4384. InitializedEntity Entity =
  4385. InitializedEntity::InitializeParameter(Context, Ty, false);
  4386. ExprResult Arg = TheCall->getArg(i);
  4387. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4388. if (Arg.isInvalid())
  4389. return true;
  4390. TheCall->setArg(i, Arg.get());
  4391. }
  4392. // Permute the arguments into a 'consistent' order.
  4393. SmallVector<Expr*, 5> SubExprs;
  4394. SubExprs.push_back(Ptr);
  4395. switch (Form) {
  4396. case Init:
  4397. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  4398. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4399. break;
  4400. case Load:
  4401. SubExprs.push_back(TheCall->getArg(1)); // Order
  4402. break;
  4403. case LoadCopy:
  4404. case Copy:
  4405. case Arithmetic:
  4406. case Xchg:
  4407. SubExprs.push_back(TheCall->getArg(2)); // Order
  4408. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4409. break;
  4410. case GNUXchg:
  4411. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  4412. SubExprs.push_back(TheCall->getArg(3)); // Order
  4413. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4414. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4415. break;
  4416. case C11CmpXchg:
  4417. SubExprs.push_back(TheCall->getArg(3)); // Order
  4418. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4419. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  4420. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4421. break;
  4422. case GNUCmpXchg:
  4423. SubExprs.push_back(TheCall->getArg(4)); // Order
  4424. SubExprs.push_back(TheCall->getArg(1)); // Val1
  4425. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  4426. SubExprs.push_back(TheCall->getArg(2)); // Val2
  4427. SubExprs.push_back(TheCall->getArg(3)); // Weak
  4428. break;
  4429. }
  4430. if (SubExprs.size() >= 2 && Form != Init) {
  4431. llvm::APSInt Result(32);
  4432. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  4433. !isValidOrderingForOp(Result.getSExtValue(), Op))
  4434. Diag(SubExprs[1]->getBeginLoc(),
  4435. diag::warn_atomic_op_has_invalid_memory_order)
  4436. << SubExprs[1]->getSourceRange();
  4437. }
  4438. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  4439. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  4440. llvm::APSInt Result(32);
  4441. if (Scope->isIntegerConstantExpr(Result, Context) &&
  4442. !ScopeModel->isValid(Result.getZExtValue())) {
  4443. Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
  4444. << Scope->getSourceRange();
  4445. }
  4446. SubExprs.push_back(Scope);
  4447. }
  4448. AtomicExpr *AE =
  4449. new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
  4450. ResultType, Op, TheCall->getRParenLoc());
  4451. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  4452. Op == AtomicExpr::AO__c11_atomic_store ||
  4453. Op == AtomicExpr::AO__opencl_atomic_load ||
  4454. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  4455. Context.AtomicUsesUnsupportedLibcall(AE))
  4456. Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
  4457. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  4458. Op == AtomicExpr::AO__opencl_atomic_load)
  4459. ? 0
  4460. : 1);
  4461. return AE;
  4462. }
  4463. /// checkBuiltinArgument - Given a call to a builtin function, perform
  4464. /// normal type-checking on the given argument, updating the call in
  4465. /// place. This is useful when a builtin function requires custom
  4466. /// type-checking for some of its arguments but not necessarily all of
  4467. /// them.
  4468. ///
  4469. /// Returns true on error.
  4470. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  4471. FunctionDecl *Fn = E->getDirectCallee();
  4472. assert(Fn && "builtin call without direct callee!");
  4473. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  4474. InitializedEntity Entity =
  4475. InitializedEntity::InitializeParameter(S.Context, Param);
  4476. ExprResult Arg = E->getArg(0);
  4477. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4478. if (Arg.isInvalid())
  4479. return true;
  4480. E->setArg(ArgIndex, Arg.get());
  4481. return false;
  4482. }
  4483. /// We have a call to a function like __sync_fetch_and_add, which is an
  4484. /// overloaded function based on the pointer type of its first argument.
  4485. /// The main ActOnCallExpr routines have already promoted the types of
  4486. /// arguments because all of these calls are prototyped as void(...).
  4487. ///
  4488. /// This function goes through and does final semantic checking for these
  4489. /// builtins, as well as generating any warnings.
  4490. ExprResult
  4491. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  4492. CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
  4493. Expr *Callee = TheCall->getCallee();
  4494. DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
  4495. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4496. // Ensure that we have at least one argument to do type inference from.
  4497. if (TheCall->getNumArgs() < 1) {
  4498. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4499. << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
  4500. return ExprError();
  4501. }
  4502. // Inspect the first argument of the atomic builtin. This should always be
  4503. // a pointer type, whose element is an integral scalar or pointer type.
  4504. // Because it is a pointer type, we don't have to worry about any implicit
  4505. // casts here.
  4506. // FIXME: We don't allow floating point scalars as input.
  4507. Expr *FirstArg = TheCall->getArg(0);
  4508. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  4509. if (FirstArgResult.isInvalid())
  4510. return ExprError();
  4511. FirstArg = FirstArgResult.get();
  4512. TheCall->setArg(0, FirstArg);
  4513. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  4514. if (!pointerType) {
  4515. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
  4516. << FirstArg->getType() << FirstArg->getSourceRange();
  4517. return ExprError();
  4518. }
  4519. QualType ValType = pointerType->getPointeeType();
  4520. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4521. !ValType->isBlockPointerType()) {
  4522. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
  4523. << FirstArg->getType() << FirstArg->getSourceRange();
  4524. return ExprError();
  4525. }
  4526. if (ValType.isConstQualified()) {
  4527. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
  4528. << FirstArg->getType() << FirstArg->getSourceRange();
  4529. return ExprError();
  4530. }
  4531. switch (ValType.getObjCLifetime()) {
  4532. case Qualifiers::OCL_None:
  4533. case Qualifiers::OCL_ExplicitNone:
  4534. // okay
  4535. break;
  4536. case Qualifiers::OCL_Weak:
  4537. case Qualifiers::OCL_Strong:
  4538. case Qualifiers::OCL_Autoreleasing:
  4539. Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
  4540. << ValType << FirstArg->getSourceRange();
  4541. return ExprError();
  4542. }
  4543. // Strip any qualifiers off ValType.
  4544. ValType = ValType.getUnqualifiedType();
  4545. // The majority of builtins return a value, but a few have special return
  4546. // types, so allow them to override appropriately below.
  4547. QualType ResultType = ValType;
  4548. // We need to figure out which concrete builtin this maps onto. For example,
  4549. // __sync_fetch_and_add with a 2 byte object turns into
  4550. // __sync_fetch_and_add_2.
  4551. #define BUILTIN_ROW(x) \
  4552. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  4553. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  4554. static const unsigned BuiltinIndices[][5] = {
  4555. BUILTIN_ROW(__sync_fetch_and_add),
  4556. BUILTIN_ROW(__sync_fetch_and_sub),
  4557. BUILTIN_ROW(__sync_fetch_and_or),
  4558. BUILTIN_ROW(__sync_fetch_and_and),
  4559. BUILTIN_ROW(__sync_fetch_and_xor),
  4560. BUILTIN_ROW(__sync_fetch_and_nand),
  4561. BUILTIN_ROW(__sync_add_and_fetch),
  4562. BUILTIN_ROW(__sync_sub_and_fetch),
  4563. BUILTIN_ROW(__sync_and_and_fetch),
  4564. BUILTIN_ROW(__sync_or_and_fetch),
  4565. BUILTIN_ROW(__sync_xor_and_fetch),
  4566. BUILTIN_ROW(__sync_nand_and_fetch),
  4567. BUILTIN_ROW(__sync_val_compare_and_swap),
  4568. BUILTIN_ROW(__sync_bool_compare_and_swap),
  4569. BUILTIN_ROW(__sync_lock_test_and_set),
  4570. BUILTIN_ROW(__sync_lock_release),
  4571. BUILTIN_ROW(__sync_swap)
  4572. };
  4573. #undef BUILTIN_ROW
  4574. // Determine the index of the size.
  4575. unsigned SizeIndex;
  4576. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  4577. case 1: SizeIndex = 0; break;
  4578. case 2: SizeIndex = 1; break;
  4579. case 4: SizeIndex = 2; break;
  4580. case 8: SizeIndex = 3; break;
  4581. case 16: SizeIndex = 4; break;
  4582. default:
  4583. Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
  4584. << FirstArg->getType() << FirstArg->getSourceRange();
  4585. return ExprError();
  4586. }
  4587. // Each of these builtins has one pointer argument, followed by some number of
  4588. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  4589. // that we ignore. Find out which row of BuiltinIndices to read from as well
  4590. // as the number of fixed args.
  4591. unsigned BuiltinID = FDecl->getBuiltinID();
  4592. unsigned BuiltinIndex, NumFixed = 1;
  4593. bool WarnAboutSemanticsChange = false;
  4594. switch (BuiltinID) {
  4595. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  4596. case Builtin::BI__sync_fetch_and_add:
  4597. case Builtin::BI__sync_fetch_and_add_1:
  4598. case Builtin::BI__sync_fetch_and_add_2:
  4599. case Builtin::BI__sync_fetch_and_add_4:
  4600. case Builtin::BI__sync_fetch_and_add_8:
  4601. case Builtin::BI__sync_fetch_and_add_16:
  4602. BuiltinIndex = 0;
  4603. break;
  4604. case Builtin::BI__sync_fetch_and_sub:
  4605. case Builtin::BI__sync_fetch_and_sub_1:
  4606. case Builtin::BI__sync_fetch_and_sub_2:
  4607. case Builtin::BI__sync_fetch_and_sub_4:
  4608. case Builtin::BI__sync_fetch_and_sub_8:
  4609. case Builtin::BI__sync_fetch_and_sub_16:
  4610. BuiltinIndex = 1;
  4611. break;
  4612. case Builtin::BI__sync_fetch_and_or:
  4613. case Builtin::BI__sync_fetch_and_or_1:
  4614. case Builtin::BI__sync_fetch_and_or_2:
  4615. case Builtin::BI__sync_fetch_and_or_4:
  4616. case Builtin::BI__sync_fetch_and_or_8:
  4617. case Builtin::BI__sync_fetch_and_or_16:
  4618. BuiltinIndex = 2;
  4619. break;
  4620. case Builtin::BI__sync_fetch_and_and:
  4621. case Builtin::BI__sync_fetch_and_and_1:
  4622. case Builtin::BI__sync_fetch_and_and_2:
  4623. case Builtin::BI__sync_fetch_and_and_4:
  4624. case Builtin::BI__sync_fetch_and_and_8:
  4625. case Builtin::BI__sync_fetch_and_and_16:
  4626. BuiltinIndex = 3;
  4627. break;
  4628. case Builtin::BI__sync_fetch_and_xor:
  4629. case Builtin::BI__sync_fetch_and_xor_1:
  4630. case Builtin::BI__sync_fetch_and_xor_2:
  4631. case Builtin::BI__sync_fetch_and_xor_4:
  4632. case Builtin::BI__sync_fetch_and_xor_8:
  4633. case Builtin::BI__sync_fetch_and_xor_16:
  4634. BuiltinIndex = 4;
  4635. break;
  4636. case Builtin::BI__sync_fetch_and_nand:
  4637. case Builtin::BI__sync_fetch_and_nand_1:
  4638. case Builtin::BI__sync_fetch_and_nand_2:
  4639. case Builtin::BI__sync_fetch_and_nand_4:
  4640. case Builtin::BI__sync_fetch_and_nand_8:
  4641. case Builtin::BI__sync_fetch_and_nand_16:
  4642. BuiltinIndex = 5;
  4643. WarnAboutSemanticsChange = true;
  4644. break;
  4645. case Builtin::BI__sync_add_and_fetch:
  4646. case Builtin::BI__sync_add_and_fetch_1:
  4647. case Builtin::BI__sync_add_and_fetch_2:
  4648. case Builtin::BI__sync_add_and_fetch_4:
  4649. case Builtin::BI__sync_add_and_fetch_8:
  4650. case Builtin::BI__sync_add_and_fetch_16:
  4651. BuiltinIndex = 6;
  4652. break;
  4653. case Builtin::BI__sync_sub_and_fetch:
  4654. case Builtin::BI__sync_sub_and_fetch_1:
  4655. case Builtin::BI__sync_sub_and_fetch_2:
  4656. case Builtin::BI__sync_sub_and_fetch_4:
  4657. case Builtin::BI__sync_sub_and_fetch_8:
  4658. case Builtin::BI__sync_sub_and_fetch_16:
  4659. BuiltinIndex = 7;
  4660. break;
  4661. case Builtin::BI__sync_and_and_fetch:
  4662. case Builtin::BI__sync_and_and_fetch_1:
  4663. case Builtin::BI__sync_and_and_fetch_2:
  4664. case Builtin::BI__sync_and_and_fetch_4:
  4665. case Builtin::BI__sync_and_and_fetch_8:
  4666. case Builtin::BI__sync_and_and_fetch_16:
  4667. BuiltinIndex = 8;
  4668. break;
  4669. case Builtin::BI__sync_or_and_fetch:
  4670. case Builtin::BI__sync_or_and_fetch_1:
  4671. case Builtin::BI__sync_or_and_fetch_2:
  4672. case Builtin::BI__sync_or_and_fetch_4:
  4673. case Builtin::BI__sync_or_and_fetch_8:
  4674. case Builtin::BI__sync_or_and_fetch_16:
  4675. BuiltinIndex = 9;
  4676. break;
  4677. case Builtin::BI__sync_xor_and_fetch:
  4678. case Builtin::BI__sync_xor_and_fetch_1:
  4679. case Builtin::BI__sync_xor_and_fetch_2:
  4680. case Builtin::BI__sync_xor_and_fetch_4:
  4681. case Builtin::BI__sync_xor_and_fetch_8:
  4682. case Builtin::BI__sync_xor_and_fetch_16:
  4683. BuiltinIndex = 10;
  4684. break;
  4685. case Builtin::BI__sync_nand_and_fetch:
  4686. case Builtin::BI__sync_nand_and_fetch_1:
  4687. case Builtin::BI__sync_nand_and_fetch_2:
  4688. case Builtin::BI__sync_nand_and_fetch_4:
  4689. case Builtin::BI__sync_nand_and_fetch_8:
  4690. case Builtin::BI__sync_nand_and_fetch_16:
  4691. BuiltinIndex = 11;
  4692. WarnAboutSemanticsChange = true;
  4693. break;
  4694. case Builtin::BI__sync_val_compare_and_swap:
  4695. case Builtin::BI__sync_val_compare_and_swap_1:
  4696. case Builtin::BI__sync_val_compare_and_swap_2:
  4697. case Builtin::BI__sync_val_compare_and_swap_4:
  4698. case Builtin::BI__sync_val_compare_and_swap_8:
  4699. case Builtin::BI__sync_val_compare_and_swap_16:
  4700. BuiltinIndex = 12;
  4701. NumFixed = 2;
  4702. break;
  4703. case Builtin::BI__sync_bool_compare_and_swap:
  4704. case Builtin::BI__sync_bool_compare_and_swap_1:
  4705. case Builtin::BI__sync_bool_compare_and_swap_2:
  4706. case Builtin::BI__sync_bool_compare_and_swap_4:
  4707. case Builtin::BI__sync_bool_compare_and_swap_8:
  4708. case Builtin::BI__sync_bool_compare_and_swap_16:
  4709. BuiltinIndex = 13;
  4710. NumFixed = 2;
  4711. ResultType = Context.BoolTy;
  4712. break;
  4713. case Builtin::BI__sync_lock_test_and_set:
  4714. case Builtin::BI__sync_lock_test_and_set_1:
  4715. case Builtin::BI__sync_lock_test_and_set_2:
  4716. case Builtin::BI__sync_lock_test_and_set_4:
  4717. case Builtin::BI__sync_lock_test_and_set_8:
  4718. case Builtin::BI__sync_lock_test_and_set_16:
  4719. BuiltinIndex = 14;
  4720. break;
  4721. case Builtin::BI__sync_lock_release:
  4722. case Builtin::BI__sync_lock_release_1:
  4723. case Builtin::BI__sync_lock_release_2:
  4724. case Builtin::BI__sync_lock_release_4:
  4725. case Builtin::BI__sync_lock_release_8:
  4726. case Builtin::BI__sync_lock_release_16:
  4727. BuiltinIndex = 15;
  4728. NumFixed = 0;
  4729. ResultType = Context.VoidTy;
  4730. break;
  4731. case Builtin::BI__sync_swap:
  4732. case Builtin::BI__sync_swap_1:
  4733. case Builtin::BI__sync_swap_2:
  4734. case Builtin::BI__sync_swap_4:
  4735. case Builtin::BI__sync_swap_8:
  4736. case Builtin::BI__sync_swap_16:
  4737. BuiltinIndex = 16;
  4738. break;
  4739. }
  4740. // Now that we know how many fixed arguments we expect, first check that we
  4741. // have at least that many.
  4742. if (TheCall->getNumArgs() < 1+NumFixed) {
  4743. Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
  4744. << 0 << 1 + NumFixed << TheCall->getNumArgs()
  4745. << Callee->getSourceRange();
  4746. return ExprError();
  4747. }
  4748. Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
  4749. << Callee->getSourceRange();
  4750. if (WarnAboutSemanticsChange) {
  4751. Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
  4752. << Callee->getSourceRange();
  4753. }
  4754. // Get the decl for the concrete builtin from this, we can tell what the
  4755. // concrete integer type we should convert to is.
  4756. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  4757. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  4758. FunctionDecl *NewBuiltinDecl;
  4759. if (NewBuiltinID == BuiltinID)
  4760. NewBuiltinDecl = FDecl;
  4761. else {
  4762. // Perform builtin lookup to avoid redeclaring it.
  4763. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  4764. LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
  4765. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  4766. assert(Res.getFoundDecl());
  4767. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  4768. if (!NewBuiltinDecl)
  4769. return ExprError();
  4770. }
  4771. // The first argument --- the pointer --- has a fixed type; we
  4772. // deduce the types of the rest of the arguments accordingly. Walk
  4773. // the remaining arguments, converting them to the deduced value type.
  4774. for (unsigned i = 0; i != NumFixed; ++i) {
  4775. ExprResult Arg = TheCall->getArg(i+1);
  4776. // GCC does an implicit conversion to the pointer or integer ValType. This
  4777. // can fail in some cases (1i -> int**), check for this error case now.
  4778. // Initialize the argument.
  4779. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  4780. ValType, /*consume*/ false);
  4781. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4782. if (Arg.isInvalid())
  4783. return ExprError();
  4784. // Okay, we have something that *can* be converted to the right type. Check
  4785. // to see if there is a potentially weird extension going on here. This can
  4786. // happen when you do an atomic operation on something like an char* and
  4787. // pass in 42. The 42 gets converted to char. This is even more strange
  4788. // for things like 45.123 -> char, etc.
  4789. // FIXME: Do this check.
  4790. TheCall->setArg(i+1, Arg.get());
  4791. }
  4792. // Create a new DeclRefExpr to refer to the new decl.
  4793. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  4794. Context,
  4795. DRE->getQualifierLoc(),
  4796. SourceLocation(),
  4797. NewBuiltinDecl,
  4798. /*enclosing*/ false,
  4799. DRE->getLocation(),
  4800. Context.BuiltinFnTy,
  4801. DRE->getValueKind());
  4802. // Set the callee in the CallExpr.
  4803. // FIXME: This loses syntactic information.
  4804. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  4805. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  4806. CK_BuiltinFnToFnPtr);
  4807. TheCall->setCallee(PromotedCall.get());
  4808. // Change the result type of the call to match the original value type. This
  4809. // is arbitrary, but the codegen for these builtins ins design to handle it
  4810. // gracefully.
  4811. TheCall->setType(ResultType);
  4812. return TheCallResult;
  4813. }
  4814. /// SemaBuiltinNontemporalOverloaded - We have a call to
  4815. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  4816. /// overloaded function based on the pointer type of its last argument.
  4817. ///
  4818. /// This function goes through and does final semantic checking for these
  4819. /// builtins.
  4820. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  4821. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  4822. DeclRefExpr *DRE =
  4823. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4824. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4825. unsigned BuiltinID = FDecl->getBuiltinID();
  4826. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  4827. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  4828. "Unexpected nontemporal load/store builtin!");
  4829. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  4830. unsigned numArgs = isStore ? 2 : 1;
  4831. // Ensure that we have the proper number of arguments.
  4832. if (checkArgCount(*this, TheCall, numArgs))
  4833. return ExprError();
  4834. // Inspect the last argument of the nontemporal builtin. This should always
  4835. // be a pointer type, from which we imply the type of the memory access.
  4836. // Because it is a pointer type, we don't have to worry about any implicit
  4837. // casts here.
  4838. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  4839. ExprResult PointerArgResult =
  4840. DefaultFunctionArrayLvalueConversion(PointerArg);
  4841. if (PointerArgResult.isInvalid())
  4842. return ExprError();
  4843. PointerArg = PointerArgResult.get();
  4844. TheCall->setArg(numArgs - 1, PointerArg);
  4845. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  4846. if (!pointerType) {
  4847. Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
  4848. << PointerArg->getType() << PointerArg->getSourceRange();
  4849. return ExprError();
  4850. }
  4851. QualType ValType = pointerType->getPointeeType();
  4852. // Strip any qualifiers off ValType.
  4853. ValType = ValType.getUnqualifiedType();
  4854. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  4855. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  4856. !ValType->isVectorType()) {
  4857. Diag(DRE->getBeginLoc(),
  4858. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  4859. << PointerArg->getType() << PointerArg->getSourceRange();
  4860. return ExprError();
  4861. }
  4862. if (!isStore) {
  4863. TheCall->setType(ValType);
  4864. return TheCallResult;
  4865. }
  4866. ExprResult ValArg = TheCall->getArg(0);
  4867. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4868. Context, ValType, /*consume*/ false);
  4869. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  4870. if (ValArg.isInvalid())
  4871. return ExprError();
  4872. TheCall->setArg(0, ValArg.get());
  4873. TheCall->setType(Context.VoidTy);
  4874. return TheCallResult;
  4875. }
  4876. /// CheckObjCString - Checks that the argument to the builtin
  4877. /// CFString constructor is correct
  4878. /// Note: It might also make sense to do the UTF-16 conversion here (would
  4879. /// simplify the backend).
  4880. bool Sema::CheckObjCString(Expr *Arg) {
  4881. Arg = Arg->IgnoreParenCasts();
  4882. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  4883. if (!Literal || !Literal->isAscii()) {
  4884. Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  4885. << Arg->getSourceRange();
  4886. return true;
  4887. }
  4888. if (Literal->containsNonAsciiOrNull()) {
  4889. StringRef String = Literal->getString();
  4890. unsigned NumBytes = String.size();
  4891. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  4892. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4893. llvm::UTF16 *ToPtr = &ToBuf[0];
  4894. llvm::ConversionResult Result =
  4895. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4896. ToPtr + NumBytes, llvm::strictConversion);
  4897. // Check for conversion failure.
  4898. if (Result != llvm::conversionOK)
  4899. Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
  4900. << Arg->getSourceRange();
  4901. }
  4902. return false;
  4903. }
  4904. /// CheckObjCString - Checks that the format string argument to the os_log()
  4905. /// and os_trace() functions is correct, and converts it to const char *.
  4906. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  4907. Arg = Arg->IgnoreParenCasts();
  4908. auto *Literal = dyn_cast<StringLiteral>(Arg);
  4909. if (!Literal) {
  4910. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  4911. Literal = ObjcLiteral->getString();
  4912. }
  4913. }
  4914. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  4915. return ExprError(
  4916. Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
  4917. << Arg->getSourceRange());
  4918. }
  4919. ExprResult Result(Literal);
  4920. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  4921. InitializedEntity Entity =
  4922. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  4923. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  4924. return Result;
  4925. }
  4926. /// Check that the user is calling the appropriate va_start builtin for the
  4927. /// target and calling convention.
  4928. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  4929. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  4930. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  4931. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  4932. bool IsWindows = TT.isOSWindows();
  4933. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  4934. if (IsX64 || IsAArch64) {
  4935. CallingConv CC = CC_C;
  4936. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  4937. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  4938. if (IsMSVAStart) {
  4939. // Don't allow this in System V ABI functions.
  4940. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  4941. return S.Diag(Fn->getBeginLoc(),
  4942. diag::err_ms_va_start_used_in_sysv_function);
  4943. } else {
  4944. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  4945. // On x64 Windows, don't allow this in System V ABI functions.
  4946. // (Yes, that means there's no corresponding way to support variadic
  4947. // System V ABI functions on Windows.)
  4948. if ((IsWindows && CC == CC_X86_64SysV) ||
  4949. (!IsWindows && CC == CC_Win64))
  4950. return S.Diag(Fn->getBeginLoc(),
  4951. diag::err_va_start_used_in_wrong_abi_function)
  4952. << !IsWindows;
  4953. }
  4954. return false;
  4955. }
  4956. if (IsMSVAStart)
  4957. return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
  4958. return false;
  4959. }
  4960. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  4961. ParmVarDecl **LastParam = nullptr) {
  4962. // Determine whether the current function, block, or obj-c method is variadic
  4963. // and get its parameter list.
  4964. bool IsVariadic = false;
  4965. ArrayRef<ParmVarDecl *> Params;
  4966. DeclContext *Caller = S.CurContext;
  4967. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  4968. IsVariadic = Block->isVariadic();
  4969. Params = Block->parameters();
  4970. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  4971. IsVariadic = FD->isVariadic();
  4972. Params = FD->parameters();
  4973. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  4974. IsVariadic = MD->isVariadic();
  4975. // FIXME: This isn't correct for methods (results in bogus warning).
  4976. Params = MD->parameters();
  4977. } else if (isa<CapturedDecl>(Caller)) {
  4978. // We don't support va_start in a CapturedDecl.
  4979. S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
  4980. return true;
  4981. } else {
  4982. // This must be some other declcontext that parses exprs.
  4983. S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
  4984. return true;
  4985. }
  4986. if (!IsVariadic) {
  4987. S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
  4988. return true;
  4989. }
  4990. if (LastParam)
  4991. *LastParam = Params.empty() ? nullptr : Params.back();
  4992. return false;
  4993. }
  4994. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  4995. /// for validity. Emit an error and return true on failure; return false
  4996. /// on success.
  4997. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  4998. Expr *Fn = TheCall->getCallee();
  4999. if (checkVAStartABI(*this, BuiltinID, Fn))
  5000. return true;
  5001. if (TheCall->getNumArgs() > 2) {
  5002. Diag(TheCall->getArg(2)->getBeginLoc(),
  5003. diag::err_typecheck_call_too_many_args)
  5004. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5005. << Fn->getSourceRange()
  5006. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5007. (*(TheCall->arg_end() - 1))->getEndLoc());
  5008. return true;
  5009. }
  5010. if (TheCall->getNumArgs() < 2) {
  5011. return Diag(TheCall->getEndLoc(),
  5012. diag::err_typecheck_call_too_few_args_at_least)
  5013. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  5014. }
  5015. // Type-check the first argument normally.
  5016. if (checkBuiltinArgument(*this, TheCall, 0))
  5017. return true;
  5018. // Check that the current function is variadic, and get its last parameter.
  5019. ParmVarDecl *LastParam;
  5020. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  5021. return true;
  5022. // Verify that the second argument to the builtin is the last argument of the
  5023. // current function or method.
  5024. bool SecondArgIsLastNamedArgument = false;
  5025. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  5026. // These are valid if SecondArgIsLastNamedArgument is false after the next
  5027. // block.
  5028. QualType Type;
  5029. SourceLocation ParamLoc;
  5030. bool IsCRegister = false;
  5031. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  5032. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  5033. SecondArgIsLastNamedArgument = PV == LastParam;
  5034. Type = PV->getType();
  5035. ParamLoc = PV->getLocation();
  5036. IsCRegister =
  5037. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  5038. }
  5039. }
  5040. if (!SecondArgIsLastNamedArgument)
  5041. Diag(TheCall->getArg(1)->getBeginLoc(),
  5042. diag::warn_second_arg_of_va_start_not_last_named_param);
  5043. else if (IsCRegister || Type->isReferenceType() ||
  5044. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  5045. // Promotable integers are UB, but enumerations need a bit of
  5046. // extra checking to see what their promotable type actually is.
  5047. if (!Type->isPromotableIntegerType())
  5048. return false;
  5049. if (!Type->isEnumeralType())
  5050. return true;
  5051. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  5052. return !(ED &&
  5053. Context.typesAreCompatible(ED->getPromotionType(), Type));
  5054. }()) {
  5055. unsigned Reason = 0;
  5056. if (Type->isReferenceType()) Reason = 1;
  5057. else if (IsCRegister) Reason = 2;
  5058. Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
  5059. Diag(ParamLoc, diag::note_parameter_type) << Type;
  5060. }
  5061. TheCall->setType(Context.VoidTy);
  5062. return false;
  5063. }
  5064. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  5065. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  5066. // const char *named_addr);
  5067. Expr *Func = Call->getCallee();
  5068. if (Call->getNumArgs() < 3)
  5069. return Diag(Call->getEndLoc(),
  5070. diag::err_typecheck_call_too_few_args_at_least)
  5071. << 0 /*function call*/ << 3 << Call->getNumArgs();
  5072. // Type-check the first argument normally.
  5073. if (checkBuiltinArgument(*this, Call, 0))
  5074. return true;
  5075. // Check that the current function is variadic.
  5076. if (checkVAStartIsInVariadicFunction(*this, Func))
  5077. return true;
  5078. // __va_start on Windows does not validate the parameter qualifiers
  5079. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  5080. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  5081. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  5082. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  5083. const QualType &ConstCharPtrTy =
  5084. Context.getPointerType(Context.CharTy.withConst());
  5085. if (!Arg1Ty->isPointerType() ||
  5086. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  5087. Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5088. << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
  5089. << 0 /* qualifier difference */
  5090. << 3 /* parameter mismatch */
  5091. << 2 << Arg1->getType() << ConstCharPtrTy;
  5092. const QualType SizeTy = Context.getSizeType();
  5093. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  5094. Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
  5095. << Arg2->getType() << SizeTy << 1 /* different class */
  5096. << 0 /* qualifier difference */
  5097. << 3 /* parameter mismatch */
  5098. << 3 << Arg2->getType() << SizeTy;
  5099. return false;
  5100. }
  5101. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  5102. /// friends. This is declared to take (...), so we have to check everything.
  5103. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  5104. if (TheCall->getNumArgs() < 2)
  5105. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5106. << 0 << 2 << TheCall->getNumArgs() /*function call*/;
  5107. if (TheCall->getNumArgs() > 2)
  5108. return Diag(TheCall->getArg(2)->getBeginLoc(),
  5109. diag::err_typecheck_call_too_many_args)
  5110. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5111. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5112. (*(TheCall->arg_end() - 1))->getEndLoc());
  5113. ExprResult OrigArg0 = TheCall->getArg(0);
  5114. ExprResult OrigArg1 = TheCall->getArg(1);
  5115. // Do standard promotions between the two arguments, returning their common
  5116. // type.
  5117. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  5118. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  5119. return true;
  5120. // Make sure any conversions are pushed back into the call; this is
  5121. // type safe since unordered compare builtins are declared as "_Bool
  5122. // foo(...)".
  5123. TheCall->setArg(0, OrigArg0.get());
  5124. TheCall->setArg(1, OrigArg1.get());
  5125. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  5126. return false;
  5127. // If the common type isn't a real floating type, then the arguments were
  5128. // invalid for this operation.
  5129. if (Res.isNull() || !Res->isRealFloatingType())
  5130. return Diag(OrigArg0.get()->getBeginLoc(),
  5131. diag::err_typecheck_call_invalid_ordered_compare)
  5132. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  5133. << SourceRange(OrigArg0.get()->getBeginLoc(),
  5134. OrigArg1.get()->getEndLoc());
  5135. return false;
  5136. }
  5137. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  5138. /// __builtin_isnan and friends. This is declared to take (...), so we have
  5139. /// to check everything. We expect the last argument to be a floating point
  5140. /// value.
  5141. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  5142. if (TheCall->getNumArgs() < NumArgs)
  5143. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5144. << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
  5145. if (TheCall->getNumArgs() > NumArgs)
  5146. return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
  5147. diag::err_typecheck_call_too_many_args)
  5148. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  5149. << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
  5150. (*(TheCall->arg_end() - 1))->getEndLoc());
  5151. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  5152. if (OrigArg->isTypeDependent())
  5153. return false;
  5154. // This operation requires a non-_Complex floating-point number.
  5155. if (!OrigArg->getType()->isRealFloatingType())
  5156. return Diag(OrigArg->getBeginLoc(),
  5157. diag::err_typecheck_call_invalid_unary_fp)
  5158. << OrigArg->getType() << OrigArg->getSourceRange();
  5159. // If this is an implicit conversion from float -> float, double, or
  5160. // long double, remove it.
  5161. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  5162. // Only remove standard FloatCasts, leaving other casts inplace
  5163. if (Cast->getCastKind() == CK_FloatingCast) {
  5164. Expr *CastArg = Cast->getSubExpr();
  5165. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  5166. assert(
  5167. (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  5168. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
  5169. Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
  5170. "promotion from float to either float, double, or long double is "
  5171. "the only expected cast here");
  5172. Cast->setSubExpr(nullptr);
  5173. TheCall->setArg(NumArgs-1, CastArg);
  5174. }
  5175. }
  5176. }
  5177. return false;
  5178. }
  5179. // Customized Sema Checking for VSX builtins that have the following signature:
  5180. // vector [...] builtinName(vector [...], vector [...], const int);
  5181. // Which takes the same type of vectors (any legal vector type) for the first
  5182. // two arguments and takes compile time constant for the third argument.
  5183. // Example builtins are :
  5184. // vector double vec_xxpermdi(vector double, vector double, int);
  5185. // vector short vec_xxsldwi(vector short, vector short, int);
  5186. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  5187. unsigned ExpectedNumArgs = 3;
  5188. if (TheCall->getNumArgs() < ExpectedNumArgs)
  5189. return Diag(TheCall->getEndLoc(),
  5190. diag::err_typecheck_call_too_few_args_at_least)
  5191. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5192. << TheCall->getSourceRange();
  5193. if (TheCall->getNumArgs() > ExpectedNumArgs)
  5194. return Diag(TheCall->getEndLoc(),
  5195. diag::err_typecheck_call_too_many_args_at_most)
  5196. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  5197. << TheCall->getSourceRange();
  5198. // Check the third argument is a compile time constant
  5199. llvm::APSInt Value;
  5200. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  5201. return Diag(TheCall->getBeginLoc(),
  5202. diag::err_vsx_builtin_nonconstant_argument)
  5203. << 3 /* argument index */ << TheCall->getDirectCallee()
  5204. << SourceRange(TheCall->getArg(2)->getBeginLoc(),
  5205. TheCall->getArg(2)->getEndLoc());
  5206. QualType Arg1Ty = TheCall->getArg(0)->getType();
  5207. QualType Arg2Ty = TheCall->getArg(1)->getType();
  5208. // Check the type of argument 1 and argument 2 are vectors.
  5209. SourceLocation BuiltinLoc = TheCall->getBeginLoc();
  5210. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  5211. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  5212. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  5213. << TheCall->getDirectCallee()
  5214. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5215. TheCall->getArg(1)->getEndLoc());
  5216. }
  5217. // Check the first two arguments are the same type.
  5218. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  5219. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  5220. << TheCall->getDirectCallee()
  5221. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5222. TheCall->getArg(1)->getEndLoc());
  5223. }
  5224. // When default clang type checking is turned off and the customized type
  5225. // checking is used, the returning type of the function must be explicitly
  5226. // set. Otherwise it is _Bool by default.
  5227. TheCall->setType(Arg1Ty);
  5228. return false;
  5229. }
  5230. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  5231. // This is declared to take (...), so we have to check everything.
  5232. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  5233. if (TheCall->getNumArgs() < 2)
  5234. return ExprError(Diag(TheCall->getEndLoc(),
  5235. diag::err_typecheck_call_too_few_args_at_least)
  5236. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  5237. << TheCall->getSourceRange());
  5238. // Determine which of the following types of shufflevector we're checking:
  5239. // 1) unary, vector mask: (lhs, mask)
  5240. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  5241. QualType resType = TheCall->getArg(0)->getType();
  5242. unsigned numElements = 0;
  5243. if (!TheCall->getArg(0)->isTypeDependent() &&
  5244. !TheCall->getArg(1)->isTypeDependent()) {
  5245. QualType LHSType = TheCall->getArg(0)->getType();
  5246. QualType RHSType = TheCall->getArg(1)->getType();
  5247. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  5248. return ExprError(
  5249. Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
  5250. << TheCall->getDirectCallee()
  5251. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5252. TheCall->getArg(1)->getEndLoc()));
  5253. numElements = LHSType->getAs<VectorType>()->getNumElements();
  5254. unsigned numResElements = TheCall->getNumArgs() - 2;
  5255. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  5256. // with mask. If so, verify that RHS is an integer vector type with the
  5257. // same number of elts as lhs.
  5258. if (TheCall->getNumArgs() == 2) {
  5259. if (!RHSType->hasIntegerRepresentation() ||
  5260. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  5261. return ExprError(Diag(TheCall->getBeginLoc(),
  5262. diag::err_vec_builtin_incompatible_vector)
  5263. << TheCall->getDirectCallee()
  5264. << SourceRange(TheCall->getArg(1)->getBeginLoc(),
  5265. TheCall->getArg(1)->getEndLoc()));
  5266. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  5267. return ExprError(Diag(TheCall->getBeginLoc(),
  5268. diag::err_vec_builtin_incompatible_vector)
  5269. << TheCall->getDirectCallee()
  5270. << SourceRange(TheCall->getArg(0)->getBeginLoc(),
  5271. TheCall->getArg(1)->getEndLoc()));
  5272. } else if (numElements != numResElements) {
  5273. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  5274. resType = Context.getVectorType(eltType, numResElements,
  5275. VectorType::GenericVector);
  5276. }
  5277. }
  5278. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  5279. if (TheCall->getArg(i)->isTypeDependent() ||
  5280. TheCall->getArg(i)->isValueDependent())
  5281. continue;
  5282. llvm::APSInt Result(32);
  5283. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  5284. return ExprError(Diag(TheCall->getBeginLoc(),
  5285. diag::err_shufflevector_nonconstant_argument)
  5286. << TheCall->getArg(i)->getSourceRange());
  5287. // Allow -1 which will be translated to undef in the IR.
  5288. if (Result.isSigned() && Result.isAllOnesValue())
  5289. continue;
  5290. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  5291. return ExprError(Diag(TheCall->getBeginLoc(),
  5292. diag::err_shufflevector_argument_too_large)
  5293. << TheCall->getArg(i)->getSourceRange());
  5294. }
  5295. SmallVector<Expr*, 32> exprs;
  5296. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  5297. exprs.push_back(TheCall->getArg(i));
  5298. TheCall->setArg(i, nullptr);
  5299. }
  5300. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  5301. TheCall->getCallee()->getBeginLoc(),
  5302. TheCall->getRParenLoc());
  5303. }
  5304. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  5305. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  5306. SourceLocation BuiltinLoc,
  5307. SourceLocation RParenLoc) {
  5308. ExprValueKind VK = VK_RValue;
  5309. ExprObjectKind OK = OK_Ordinary;
  5310. QualType DstTy = TInfo->getType();
  5311. QualType SrcTy = E->getType();
  5312. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  5313. return ExprError(Diag(BuiltinLoc,
  5314. diag::err_convertvector_non_vector)
  5315. << E->getSourceRange());
  5316. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  5317. return ExprError(Diag(BuiltinLoc,
  5318. diag::err_convertvector_non_vector_type));
  5319. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  5320. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  5321. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  5322. if (SrcElts != DstElts)
  5323. return ExprError(Diag(BuiltinLoc,
  5324. diag::err_convertvector_incompatible_vector)
  5325. << E->getSourceRange());
  5326. }
  5327. return new (Context)
  5328. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5329. }
  5330. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  5331. // This is declared to take (const void*, ...) and can take two
  5332. // optional constant int args.
  5333. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  5334. unsigned NumArgs = TheCall->getNumArgs();
  5335. if (NumArgs > 3)
  5336. return Diag(TheCall->getEndLoc(),
  5337. diag::err_typecheck_call_too_many_args_at_most)
  5338. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5339. // Argument 0 is checked for us and the remaining arguments must be
  5340. // constant integers.
  5341. for (unsigned i = 1; i != NumArgs; ++i)
  5342. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  5343. return true;
  5344. return false;
  5345. }
  5346. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  5347. // __assume does not evaluate its arguments, and should warn if its argument
  5348. // has side effects.
  5349. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  5350. Expr *Arg = TheCall->getArg(0);
  5351. if (Arg->isInstantiationDependent()) return false;
  5352. if (Arg->HasSideEffects(Context))
  5353. Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
  5354. << Arg->getSourceRange()
  5355. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  5356. return false;
  5357. }
  5358. /// Handle __builtin_alloca_with_align. This is declared
  5359. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  5360. /// than 8.
  5361. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  5362. // The alignment must be a constant integer.
  5363. Expr *Arg = TheCall->getArg(1);
  5364. // We can't check the value of a dependent argument.
  5365. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5366. if (const auto *UE =
  5367. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  5368. if (UE->getKind() == UETT_AlignOf ||
  5369. UE->getKind() == UETT_PreferredAlignOf)
  5370. Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
  5371. << Arg->getSourceRange();
  5372. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  5373. if (!Result.isPowerOf2())
  5374. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5375. << Arg->getSourceRange();
  5376. if (Result < Context.getCharWidth())
  5377. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
  5378. << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
  5379. if (Result > std::numeric_limits<int32_t>::max())
  5380. return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
  5381. << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
  5382. }
  5383. return false;
  5384. }
  5385. /// Handle __builtin_assume_aligned. This is declared
  5386. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  5387. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  5388. unsigned NumArgs = TheCall->getNumArgs();
  5389. if (NumArgs > 3)
  5390. return Diag(TheCall->getEndLoc(),
  5391. diag::err_typecheck_call_too_many_args_at_most)
  5392. << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
  5393. // The alignment must be a constant integer.
  5394. Expr *Arg = TheCall->getArg(1);
  5395. // We can't check the value of a dependent argument.
  5396. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  5397. llvm::APSInt Result;
  5398. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5399. return true;
  5400. if (!Result.isPowerOf2())
  5401. return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
  5402. << Arg->getSourceRange();
  5403. }
  5404. if (NumArgs > 2) {
  5405. ExprResult Arg(TheCall->getArg(2));
  5406. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  5407. Context.getSizeType(), false);
  5408. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5409. if (Arg.isInvalid()) return true;
  5410. TheCall->setArg(2, Arg.get());
  5411. }
  5412. return false;
  5413. }
  5414. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  5415. unsigned BuiltinID =
  5416. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  5417. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  5418. unsigned NumArgs = TheCall->getNumArgs();
  5419. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  5420. if (NumArgs < NumRequiredArgs) {
  5421. return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
  5422. << 0 /* function call */ << NumRequiredArgs << NumArgs
  5423. << TheCall->getSourceRange();
  5424. }
  5425. if (NumArgs >= NumRequiredArgs + 0x100) {
  5426. return Diag(TheCall->getEndLoc(),
  5427. diag::err_typecheck_call_too_many_args_at_most)
  5428. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  5429. << TheCall->getSourceRange();
  5430. }
  5431. unsigned i = 0;
  5432. // For formatting call, check buffer arg.
  5433. if (!IsSizeCall) {
  5434. ExprResult Arg(TheCall->getArg(i));
  5435. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5436. Context, Context.VoidPtrTy, false);
  5437. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5438. if (Arg.isInvalid())
  5439. return true;
  5440. TheCall->setArg(i, Arg.get());
  5441. i++;
  5442. }
  5443. // Check string literal arg.
  5444. unsigned FormatIdx = i;
  5445. {
  5446. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  5447. if (Arg.isInvalid())
  5448. return true;
  5449. TheCall->setArg(i, Arg.get());
  5450. i++;
  5451. }
  5452. // Make sure variadic args are scalar.
  5453. unsigned FirstDataArg = i;
  5454. while (i < NumArgs) {
  5455. ExprResult Arg = DefaultVariadicArgumentPromotion(
  5456. TheCall->getArg(i), VariadicFunction, nullptr);
  5457. if (Arg.isInvalid())
  5458. return true;
  5459. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  5460. if (ArgSize.getQuantity() >= 0x100) {
  5461. return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
  5462. << i << (int)ArgSize.getQuantity() << 0xff
  5463. << TheCall->getSourceRange();
  5464. }
  5465. TheCall->setArg(i, Arg.get());
  5466. i++;
  5467. }
  5468. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  5469. // call to avoid duplicate diagnostics.
  5470. if (!IsSizeCall) {
  5471. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  5472. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  5473. bool Success = CheckFormatArguments(
  5474. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  5475. VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
  5476. CheckedVarArgs);
  5477. if (!Success)
  5478. return true;
  5479. }
  5480. if (IsSizeCall) {
  5481. TheCall->setType(Context.getSizeType());
  5482. } else {
  5483. TheCall->setType(Context.VoidPtrTy);
  5484. }
  5485. return false;
  5486. }
  5487. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  5488. /// TheCall is a constant expression.
  5489. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  5490. llvm::APSInt &Result) {
  5491. Expr *Arg = TheCall->getArg(ArgNum);
  5492. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  5493. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  5494. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  5495. if (!Arg->isIntegerConstantExpr(Result, Context))
  5496. return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
  5497. << FDecl->getDeclName() << Arg->getSourceRange();
  5498. return false;
  5499. }
  5500. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  5501. /// TheCall is a constant expression in the range [Low, High].
  5502. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  5503. int Low, int High, bool RangeIsError) {
  5504. llvm::APSInt Result;
  5505. // We can't check the value of a dependent argument.
  5506. Expr *Arg = TheCall->getArg(ArgNum);
  5507. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5508. return false;
  5509. // Check constant-ness first.
  5510. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5511. return true;
  5512. if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
  5513. if (RangeIsError)
  5514. return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
  5515. << Result.toString(10) << Low << High << Arg->getSourceRange();
  5516. else
  5517. // Defer the warning until we know if the code will be emitted so that
  5518. // dead code can ignore this.
  5519. DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
  5520. PDiag(diag::warn_argument_invalid_range)
  5521. << Result.toString(10) << Low << High
  5522. << Arg->getSourceRange());
  5523. }
  5524. return false;
  5525. }
  5526. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  5527. /// TheCall is a constant expression is a multiple of Num..
  5528. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  5529. unsigned Num) {
  5530. llvm::APSInt Result;
  5531. // We can't check the value of a dependent argument.
  5532. Expr *Arg = TheCall->getArg(ArgNum);
  5533. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5534. return false;
  5535. // Check constant-ness first.
  5536. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  5537. return true;
  5538. if (Result.getSExtValue() % Num != 0)
  5539. return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
  5540. << Num << Arg->getSourceRange();
  5541. return false;
  5542. }
  5543. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  5544. /// TheCall is an ARM/AArch64 special register string literal.
  5545. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  5546. int ArgNum, unsigned ExpectedFieldNum,
  5547. bool AllowName) {
  5548. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  5549. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  5550. BuiltinID == ARM::BI__builtin_arm_rsr ||
  5551. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  5552. BuiltinID == ARM::BI__builtin_arm_wsr ||
  5553. BuiltinID == ARM::BI__builtin_arm_wsrp;
  5554. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  5555. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  5556. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  5557. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  5558. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  5559. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  5560. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  5561. // We can't check the value of a dependent argument.
  5562. Expr *Arg = TheCall->getArg(ArgNum);
  5563. if (Arg->isTypeDependent() || Arg->isValueDependent())
  5564. return false;
  5565. // Check if the argument is a string literal.
  5566. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  5567. return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
  5568. << Arg->getSourceRange();
  5569. // Check the type of special register given.
  5570. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  5571. SmallVector<StringRef, 6> Fields;
  5572. Reg.split(Fields, ":");
  5573. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  5574. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5575. << Arg->getSourceRange();
  5576. // If the string is the name of a register then we cannot check that it is
  5577. // valid here but if the string is of one the forms described in ACLE then we
  5578. // can check that the supplied fields are integers and within the valid
  5579. // ranges.
  5580. if (Fields.size() > 1) {
  5581. bool FiveFields = Fields.size() == 5;
  5582. bool ValidString = true;
  5583. if (IsARMBuiltin) {
  5584. ValidString &= Fields[0].startswith_lower("cp") ||
  5585. Fields[0].startswith_lower("p");
  5586. if (ValidString)
  5587. Fields[0] =
  5588. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  5589. ValidString &= Fields[2].startswith_lower("c");
  5590. if (ValidString)
  5591. Fields[2] = Fields[2].drop_front(1);
  5592. if (FiveFields) {
  5593. ValidString &= Fields[3].startswith_lower("c");
  5594. if (ValidString)
  5595. Fields[3] = Fields[3].drop_front(1);
  5596. }
  5597. }
  5598. SmallVector<int, 5> Ranges;
  5599. if (FiveFields)
  5600. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  5601. else
  5602. Ranges.append({15, 7, 15});
  5603. for (unsigned i=0; i<Fields.size(); ++i) {
  5604. int IntField;
  5605. ValidString &= !Fields[i].getAsInteger(10, IntField);
  5606. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  5607. }
  5608. if (!ValidString)
  5609. return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
  5610. << Arg->getSourceRange();
  5611. } else if (IsAArch64Builtin && Fields.size() == 1) {
  5612. // If the register name is one of those that appear in the condition below
  5613. // and the special register builtin being used is one of the write builtins,
  5614. // then we require that the argument provided for writing to the register
  5615. // is an integer constant expression. This is because it will be lowered to
  5616. // an MSR (immediate) instruction, so we need to know the immediate at
  5617. // compile time.
  5618. if (TheCall->getNumArgs() != 2)
  5619. return false;
  5620. std::string RegLower = Reg.lower();
  5621. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  5622. RegLower != "pan" && RegLower != "uao")
  5623. return false;
  5624. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  5625. }
  5626. return false;
  5627. }
  5628. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  5629. /// This checks that the target supports __builtin_longjmp and
  5630. /// that val is a constant 1.
  5631. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  5632. if (!Context.getTargetInfo().hasSjLjLowering())
  5633. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
  5634. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5635. Expr *Arg = TheCall->getArg(1);
  5636. llvm::APSInt Result;
  5637. // TODO: This is less than ideal. Overload this to take a value.
  5638. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  5639. return true;
  5640. if (Result != 1)
  5641. return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
  5642. << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
  5643. return false;
  5644. }
  5645. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  5646. /// This checks that the target supports __builtin_setjmp.
  5647. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  5648. if (!Context.getTargetInfo().hasSjLjLowering())
  5649. return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
  5650. << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
  5651. return false;
  5652. }
  5653. namespace {
  5654. class UncoveredArgHandler {
  5655. enum { Unknown = -1, AllCovered = -2 };
  5656. signed FirstUncoveredArg = Unknown;
  5657. SmallVector<const Expr *, 4> DiagnosticExprs;
  5658. public:
  5659. UncoveredArgHandler() = default;
  5660. bool hasUncoveredArg() const {
  5661. return (FirstUncoveredArg >= 0);
  5662. }
  5663. unsigned getUncoveredArg() const {
  5664. assert(hasUncoveredArg() && "no uncovered argument");
  5665. return FirstUncoveredArg;
  5666. }
  5667. void setAllCovered() {
  5668. // A string has been found with all arguments covered, so clear out
  5669. // the diagnostics.
  5670. DiagnosticExprs.clear();
  5671. FirstUncoveredArg = AllCovered;
  5672. }
  5673. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  5674. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  5675. // Don't update if a previous string covers all arguments.
  5676. if (FirstUncoveredArg == AllCovered)
  5677. return;
  5678. // UncoveredArgHandler tracks the highest uncovered argument index
  5679. // and with it all the strings that match this index.
  5680. if (NewFirstUncoveredArg == FirstUncoveredArg)
  5681. DiagnosticExprs.push_back(StrExpr);
  5682. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  5683. DiagnosticExprs.clear();
  5684. DiagnosticExprs.push_back(StrExpr);
  5685. FirstUncoveredArg = NewFirstUncoveredArg;
  5686. }
  5687. }
  5688. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  5689. };
  5690. enum StringLiteralCheckType {
  5691. SLCT_NotALiteral,
  5692. SLCT_UncheckedLiteral,
  5693. SLCT_CheckedLiteral
  5694. };
  5695. } // namespace
  5696. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  5697. BinaryOperatorKind BinOpKind,
  5698. bool AddendIsRight) {
  5699. unsigned BitWidth = Offset.getBitWidth();
  5700. unsigned AddendBitWidth = Addend.getBitWidth();
  5701. // There might be negative interim results.
  5702. if (Addend.isUnsigned()) {
  5703. Addend = Addend.zext(++AddendBitWidth);
  5704. Addend.setIsSigned(true);
  5705. }
  5706. // Adjust the bit width of the APSInts.
  5707. if (AddendBitWidth > BitWidth) {
  5708. Offset = Offset.sext(AddendBitWidth);
  5709. BitWidth = AddendBitWidth;
  5710. } else if (BitWidth > AddendBitWidth) {
  5711. Addend = Addend.sext(BitWidth);
  5712. }
  5713. bool Ov = false;
  5714. llvm::APSInt ResOffset = Offset;
  5715. if (BinOpKind == BO_Add)
  5716. ResOffset = Offset.sadd_ov(Addend, Ov);
  5717. else {
  5718. assert(AddendIsRight && BinOpKind == BO_Sub &&
  5719. "operator must be add or sub with addend on the right");
  5720. ResOffset = Offset.ssub_ov(Addend, Ov);
  5721. }
  5722. // We add an offset to a pointer here so we should support an offset as big as
  5723. // possible.
  5724. if (Ov) {
  5725. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  5726. "index (intermediate) result too big");
  5727. Offset = Offset.sext(2 * BitWidth);
  5728. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  5729. return;
  5730. }
  5731. Offset = ResOffset;
  5732. }
  5733. namespace {
  5734. // This is a wrapper class around StringLiteral to support offsetted string
  5735. // literals as format strings. It takes the offset into account when returning
  5736. // the string and its length or the source locations to display notes correctly.
  5737. class FormatStringLiteral {
  5738. const StringLiteral *FExpr;
  5739. int64_t Offset;
  5740. public:
  5741. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  5742. : FExpr(fexpr), Offset(Offset) {}
  5743. StringRef getString() const {
  5744. return FExpr->getString().drop_front(Offset);
  5745. }
  5746. unsigned getByteLength() const {
  5747. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  5748. }
  5749. unsigned getLength() const { return FExpr->getLength() - Offset; }
  5750. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  5751. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  5752. QualType getType() const { return FExpr->getType(); }
  5753. bool isAscii() const { return FExpr->isAscii(); }
  5754. bool isWide() const { return FExpr->isWide(); }
  5755. bool isUTF8() const { return FExpr->isUTF8(); }
  5756. bool isUTF16() const { return FExpr->isUTF16(); }
  5757. bool isUTF32() const { return FExpr->isUTF32(); }
  5758. bool isPascal() const { return FExpr->isPascal(); }
  5759. SourceLocation getLocationOfByte(
  5760. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  5761. const TargetInfo &Target, unsigned *StartToken = nullptr,
  5762. unsigned *StartTokenByteOffset = nullptr) const {
  5763. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  5764. StartToken, StartTokenByteOffset);
  5765. }
  5766. SourceLocation getBeginLoc() const LLVM_READONLY {
  5767. return FExpr->getBeginLoc().getLocWithOffset(Offset);
  5768. }
  5769. SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
  5770. };
  5771. } // namespace
  5772. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5773. const Expr *OrigFormatExpr,
  5774. ArrayRef<const Expr *> Args,
  5775. bool HasVAListArg, unsigned format_idx,
  5776. unsigned firstDataArg,
  5777. Sema::FormatStringType Type,
  5778. bool inFunctionCall,
  5779. Sema::VariadicCallType CallType,
  5780. llvm::SmallBitVector &CheckedVarArgs,
  5781. UncoveredArgHandler &UncoveredArg);
  5782. // Determine if an expression is a string literal or constant string.
  5783. // If this function returns false on the arguments to a function expecting a
  5784. // format string, we will usually need to emit a warning.
  5785. // True string literals are then checked by CheckFormatString.
  5786. static StringLiteralCheckType
  5787. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  5788. bool HasVAListArg, unsigned format_idx,
  5789. unsigned firstDataArg, Sema::FormatStringType Type,
  5790. Sema::VariadicCallType CallType, bool InFunctionCall,
  5791. llvm::SmallBitVector &CheckedVarArgs,
  5792. UncoveredArgHandler &UncoveredArg,
  5793. llvm::APSInt Offset) {
  5794. tryAgain:
  5795. assert(Offset.isSigned() && "invalid offset");
  5796. if (E->isTypeDependent() || E->isValueDependent())
  5797. return SLCT_NotALiteral;
  5798. E = E->IgnoreParenCasts();
  5799. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  5800. // Technically -Wformat-nonliteral does not warn about this case.
  5801. // The behavior of printf and friends in this case is implementation
  5802. // dependent. Ideally if the format string cannot be null then
  5803. // it should have a 'nonnull' attribute in the function prototype.
  5804. return SLCT_UncheckedLiteral;
  5805. switch (E->getStmtClass()) {
  5806. case Stmt::BinaryConditionalOperatorClass:
  5807. case Stmt::ConditionalOperatorClass: {
  5808. // The expression is a literal if both sub-expressions were, and it was
  5809. // completely checked only if both sub-expressions were checked.
  5810. const AbstractConditionalOperator *C =
  5811. cast<AbstractConditionalOperator>(E);
  5812. // Determine whether it is necessary to check both sub-expressions, for
  5813. // example, because the condition expression is a constant that can be
  5814. // evaluated at compile time.
  5815. bool CheckLeft = true, CheckRight = true;
  5816. bool Cond;
  5817. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  5818. if (Cond)
  5819. CheckRight = false;
  5820. else
  5821. CheckLeft = false;
  5822. }
  5823. // We need to maintain the offsets for the right and the left hand side
  5824. // separately to check if every possible indexed expression is a valid
  5825. // string literal. They might have different offsets for different string
  5826. // literals in the end.
  5827. StringLiteralCheckType Left;
  5828. if (!CheckLeft)
  5829. Left = SLCT_UncheckedLiteral;
  5830. else {
  5831. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  5832. HasVAListArg, format_idx, firstDataArg,
  5833. Type, CallType, InFunctionCall,
  5834. CheckedVarArgs, UncoveredArg, Offset);
  5835. if (Left == SLCT_NotALiteral || !CheckRight) {
  5836. return Left;
  5837. }
  5838. }
  5839. StringLiteralCheckType Right =
  5840. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  5841. HasVAListArg, format_idx, firstDataArg,
  5842. Type, CallType, InFunctionCall, CheckedVarArgs,
  5843. UncoveredArg, Offset);
  5844. return (CheckLeft && Left < Right) ? Left : Right;
  5845. }
  5846. case Stmt::ImplicitCastExprClass:
  5847. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  5848. goto tryAgain;
  5849. case Stmt::OpaqueValueExprClass:
  5850. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  5851. E = src;
  5852. goto tryAgain;
  5853. }
  5854. return SLCT_NotALiteral;
  5855. case Stmt::PredefinedExprClass:
  5856. // While __func__, etc., are technically not string literals, they
  5857. // cannot contain format specifiers and thus are not a security
  5858. // liability.
  5859. return SLCT_UncheckedLiteral;
  5860. case Stmt::DeclRefExprClass: {
  5861. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5862. // As an exception, do not flag errors for variables binding to
  5863. // const string literals.
  5864. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  5865. bool isConstant = false;
  5866. QualType T = DR->getType();
  5867. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  5868. isConstant = AT->getElementType().isConstant(S.Context);
  5869. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  5870. isConstant = T.isConstant(S.Context) &&
  5871. PT->getPointeeType().isConstant(S.Context);
  5872. } else if (T->isObjCObjectPointerType()) {
  5873. // In ObjC, there is usually no "const ObjectPointer" type,
  5874. // so don't check if the pointee type is constant.
  5875. isConstant = T.isConstant(S.Context);
  5876. }
  5877. if (isConstant) {
  5878. if (const Expr *Init = VD->getAnyInitializer()) {
  5879. // Look through initializers like const char c[] = { "foo" }
  5880. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  5881. if (InitList->isStringLiteralInit())
  5882. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  5883. }
  5884. return checkFormatStringExpr(S, Init, Args,
  5885. HasVAListArg, format_idx,
  5886. firstDataArg, Type, CallType,
  5887. /*InFunctionCall*/ false, CheckedVarArgs,
  5888. UncoveredArg, Offset);
  5889. }
  5890. }
  5891. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  5892. // special check to see if the format string is a function parameter
  5893. // of the function calling the printf function. If the function
  5894. // has an attribute indicating it is a printf-like function, then we
  5895. // should suppress warnings concerning non-literals being used in a call
  5896. // to a vprintf function. For example:
  5897. //
  5898. // void
  5899. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  5900. // va_list ap;
  5901. // va_start(ap, fmt);
  5902. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  5903. // ...
  5904. // }
  5905. if (HasVAListArg) {
  5906. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  5907. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  5908. int PVIndex = PV->getFunctionScopeIndex() + 1;
  5909. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  5910. // adjust for implicit parameter
  5911. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  5912. if (MD->isInstance())
  5913. ++PVIndex;
  5914. // We also check if the formats are compatible.
  5915. // We can't pass a 'scanf' string to a 'printf' function.
  5916. if (PVIndex == PVFormat->getFormatIdx() &&
  5917. Type == S.GetFormatStringType(PVFormat))
  5918. return SLCT_UncheckedLiteral;
  5919. }
  5920. }
  5921. }
  5922. }
  5923. }
  5924. return SLCT_NotALiteral;
  5925. }
  5926. case Stmt::CallExprClass:
  5927. case Stmt::CXXMemberCallExprClass: {
  5928. const CallExpr *CE = cast<CallExpr>(E);
  5929. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  5930. bool IsFirst = true;
  5931. StringLiteralCheckType CommonResult;
  5932. for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
  5933. const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
  5934. StringLiteralCheckType Result = checkFormatStringExpr(
  5935. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5936. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5937. if (IsFirst) {
  5938. CommonResult = Result;
  5939. IsFirst = false;
  5940. }
  5941. }
  5942. if (!IsFirst)
  5943. return CommonResult;
  5944. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  5945. unsigned BuiltinID = FD->getBuiltinID();
  5946. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  5947. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  5948. const Expr *Arg = CE->getArg(0);
  5949. return checkFormatStringExpr(S, Arg, Args,
  5950. HasVAListArg, format_idx,
  5951. firstDataArg, Type, CallType,
  5952. InFunctionCall, CheckedVarArgs,
  5953. UncoveredArg, Offset);
  5954. }
  5955. }
  5956. }
  5957. return SLCT_NotALiteral;
  5958. }
  5959. case Stmt::ObjCMessageExprClass: {
  5960. const auto *ME = cast<ObjCMessageExpr>(E);
  5961. if (const auto *ND = ME->getMethodDecl()) {
  5962. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  5963. const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
  5964. return checkFormatStringExpr(
  5965. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  5966. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  5967. }
  5968. }
  5969. return SLCT_NotALiteral;
  5970. }
  5971. case Stmt::ObjCStringLiteralClass:
  5972. case Stmt::StringLiteralClass: {
  5973. const StringLiteral *StrE = nullptr;
  5974. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  5975. StrE = ObjCFExpr->getString();
  5976. else
  5977. StrE = cast<StringLiteral>(E);
  5978. if (StrE) {
  5979. if (Offset.isNegative() || Offset > StrE->getLength()) {
  5980. // TODO: It would be better to have an explicit warning for out of
  5981. // bounds literals.
  5982. return SLCT_NotALiteral;
  5983. }
  5984. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  5985. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  5986. firstDataArg, Type, InFunctionCall, CallType,
  5987. CheckedVarArgs, UncoveredArg);
  5988. return SLCT_CheckedLiteral;
  5989. }
  5990. return SLCT_NotALiteral;
  5991. }
  5992. case Stmt::BinaryOperatorClass: {
  5993. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  5994. // A string literal + an int offset is still a string literal.
  5995. if (BinOp->isAdditiveOp()) {
  5996. Expr::EvalResult LResult, RResult;
  5997. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  5998. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  5999. if (LIsInt != RIsInt) {
  6000. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  6001. if (LIsInt) {
  6002. if (BinOpKind == BO_Add) {
  6003. sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
  6004. E = BinOp->getRHS();
  6005. goto tryAgain;
  6006. }
  6007. } else {
  6008. sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
  6009. E = BinOp->getLHS();
  6010. goto tryAgain;
  6011. }
  6012. }
  6013. }
  6014. return SLCT_NotALiteral;
  6015. }
  6016. case Stmt::UnaryOperatorClass: {
  6017. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  6018. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  6019. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  6020. Expr::EvalResult IndexResult;
  6021. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  6022. sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
  6023. /*RHS is int*/ true);
  6024. E = ASE->getBase();
  6025. goto tryAgain;
  6026. }
  6027. }
  6028. return SLCT_NotALiteral;
  6029. }
  6030. default:
  6031. return SLCT_NotALiteral;
  6032. }
  6033. }
  6034. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  6035. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  6036. .Case("scanf", FST_Scanf)
  6037. .Cases("printf", "printf0", FST_Printf)
  6038. .Cases("NSString", "CFString", FST_NSString)
  6039. .Case("strftime", FST_Strftime)
  6040. .Case("strfmon", FST_Strfmon)
  6041. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  6042. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  6043. .Case("os_trace", FST_OSLog)
  6044. .Case("os_log", FST_OSLog)
  6045. .Default(FST_Unknown);
  6046. }
  6047. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  6048. /// functions) for correct use of format strings.
  6049. /// Returns true if a format string has been fully checked.
  6050. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  6051. ArrayRef<const Expr *> Args,
  6052. bool IsCXXMember,
  6053. VariadicCallType CallType,
  6054. SourceLocation Loc, SourceRange Range,
  6055. llvm::SmallBitVector &CheckedVarArgs) {
  6056. FormatStringInfo FSI;
  6057. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  6058. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  6059. FSI.FirstDataArg, GetFormatStringType(Format),
  6060. CallType, Loc, Range, CheckedVarArgs);
  6061. return false;
  6062. }
  6063. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  6064. bool HasVAListArg, unsigned format_idx,
  6065. unsigned firstDataArg, FormatStringType Type,
  6066. VariadicCallType CallType,
  6067. SourceLocation Loc, SourceRange Range,
  6068. llvm::SmallBitVector &CheckedVarArgs) {
  6069. // CHECK: printf/scanf-like function is called with no format string.
  6070. if (format_idx >= Args.size()) {
  6071. Diag(Loc, diag::warn_missing_format_string) << Range;
  6072. return false;
  6073. }
  6074. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  6075. // CHECK: format string is not a string literal.
  6076. //
  6077. // Dynamically generated format strings are difficult to
  6078. // automatically vet at compile time. Requiring that format strings
  6079. // are string literals: (1) permits the checking of format strings by
  6080. // the compiler and thereby (2) can practically remove the source of
  6081. // many format string exploits.
  6082. // Format string can be either ObjC string (e.g. @"%d") or
  6083. // C string (e.g. "%d")
  6084. // ObjC string uses the same format specifiers as C string, so we can use
  6085. // the same format string checking logic for both ObjC and C strings.
  6086. UncoveredArgHandler UncoveredArg;
  6087. StringLiteralCheckType CT =
  6088. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  6089. format_idx, firstDataArg, Type, CallType,
  6090. /*IsFunctionCall*/ true, CheckedVarArgs,
  6091. UncoveredArg,
  6092. /*no string offset*/ llvm::APSInt(64, false) = 0);
  6093. // Generate a diagnostic where an uncovered argument is detected.
  6094. if (UncoveredArg.hasUncoveredArg()) {
  6095. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  6096. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  6097. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  6098. }
  6099. if (CT != SLCT_NotALiteral)
  6100. // Literal format string found, check done!
  6101. return CT == SLCT_CheckedLiteral;
  6102. // Strftime is particular as it always uses a single 'time' argument,
  6103. // so it is safe to pass a non-literal string.
  6104. if (Type == FST_Strftime)
  6105. return false;
  6106. // Do not emit diag when the string param is a macro expansion and the
  6107. // format is either NSString or CFString. This is a hack to prevent
  6108. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  6109. // which are usually used in place of NS and CF string literals.
  6110. SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
  6111. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  6112. return false;
  6113. // If there are no arguments specified, warn with -Wformat-security, otherwise
  6114. // warn only with -Wformat-nonliteral.
  6115. if (Args.size() == firstDataArg) {
  6116. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  6117. << OrigFormatExpr->getSourceRange();
  6118. switch (Type) {
  6119. default:
  6120. break;
  6121. case FST_Kprintf:
  6122. case FST_FreeBSDKPrintf:
  6123. case FST_Printf:
  6124. Diag(FormatLoc, diag::note_format_security_fixit)
  6125. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  6126. break;
  6127. case FST_NSString:
  6128. Diag(FormatLoc, diag::note_format_security_fixit)
  6129. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  6130. break;
  6131. }
  6132. } else {
  6133. Diag(FormatLoc, diag::warn_format_nonliteral)
  6134. << OrigFormatExpr->getSourceRange();
  6135. }
  6136. return false;
  6137. }
  6138. namespace {
  6139. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  6140. protected:
  6141. Sema &S;
  6142. const FormatStringLiteral *FExpr;
  6143. const Expr *OrigFormatExpr;
  6144. const Sema::FormatStringType FSType;
  6145. const unsigned FirstDataArg;
  6146. const unsigned NumDataArgs;
  6147. const char *Beg; // Start of format string.
  6148. const bool HasVAListArg;
  6149. ArrayRef<const Expr *> Args;
  6150. unsigned FormatIdx;
  6151. llvm::SmallBitVector CoveredArgs;
  6152. bool usesPositionalArgs = false;
  6153. bool atFirstArg = true;
  6154. bool inFunctionCall;
  6155. Sema::VariadicCallType CallType;
  6156. llvm::SmallBitVector &CheckedVarArgs;
  6157. UncoveredArgHandler &UncoveredArg;
  6158. public:
  6159. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  6160. const Expr *origFormatExpr,
  6161. const Sema::FormatStringType type, unsigned firstDataArg,
  6162. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  6163. ArrayRef<const Expr *> Args, unsigned formatIdx,
  6164. bool inFunctionCall, Sema::VariadicCallType callType,
  6165. llvm::SmallBitVector &CheckedVarArgs,
  6166. UncoveredArgHandler &UncoveredArg)
  6167. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  6168. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  6169. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  6170. inFunctionCall(inFunctionCall), CallType(callType),
  6171. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  6172. CoveredArgs.resize(numDataArgs);
  6173. CoveredArgs.reset();
  6174. }
  6175. void DoneProcessing();
  6176. void HandleIncompleteSpecifier(const char *startSpecifier,
  6177. unsigned specifierLen) override;
  6178. void HandleInvalidLengthModifier(
  6179. const analyze_format_string::FormatSpecifier &FS,
  6180. const analyze_format_string::ConversionSpecifier &CS,
  6181. const char *startSpecifier, unsigned specifierLen,
  6182. unsigned DiagID);
  6183. void HandleNonStandardLengthModifier(
  6184. const analyze_format_string::FormatSpecifier &FS,
  6185. const char *startSpecifier, unsigned specifierLen);
  6186. void HandleNonStandardConversionSpecifier(
  6187. const analyze_format_string::ConversionSpecifier &CS,
  6188. const char *startSpecifier, unsigned specifierLen);
  6189. void HandlePosition(const char *startPos, unsigned posLen) override;
  6190. void HandleInvalidPosition(const char *startSpecifier,
  6191. unsigned specifierLen,
  6192. analyze_format_string::PositionContext p) override;
  6193. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  6194. void HandleNullChar(const char *nullCharacter) override;
  6195. template <typename Range>
  6196. static void
  6197. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  6198. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  6199. bool IsStringLocation, Range StringRange,
  6200. ArrayRef<FixItHint> Fixit = None);
  6201. protected:
  6202. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  6203. const char *startSpec,
  6204. unsigned specifierLen,
  6205. const char *csStart, unsigned csLen);
  6206. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6207. const char *startSpec,
  6208. unsigned specifierLen);
  6209. SourceRange getFormatStringRange();
  6210. CharSourceRange getSpecifierRange(const char *startSpecifier,
  6211. unsigned specifierLen);
  6212. SourceLocation getLocationOfByte(const char *x);
  6213. const Expr *getDataArg(unsigned i) const;
  6214. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  6215. const analyze_format_string::ConversionSpecifier &CS,
  6216. const char *startSpecifier, unsigned specifierLen,
  6217. unsigned argIndex);
  6218. template <typename Range>
  6219. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  6220. bool IsStringLocation, Range StringRange,
  6221. ArrayRef<FixItHint> Fixit = None);
  6222. };
  6223. } // namespace
  6224. SourceRange CheckFormatHandler::getFormatStringRange() {
  6225. return OrigFormatExpr->getSourceRange();
  6226. }
  6227. CharSourceRange CheckFormatHandler::
  6228. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  6229. SourceLocation Start = getLocationOfByte(startSpecifier);
  6230. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  6231. // Advance the end SourceLocation by one due to half-open ranges.
  6232. End = End.getLocWithOffset(1);
  6233. return CharSourceRange::getCharRange(Start, End);
  6234. }
  6235. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  6236. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  6237. S.getLangOpts(), S.Context.getTargetInfo());
  6238. }
  6239. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  6240. unsigned specifierLen){
  6241. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  6242. getLocationOfByte(startSpecifier),
  6243. /*IsStringLocation*/true,
  6244. getSpecifierRange(startSpecifier, specifierLen));
  6245. }
  6246. void CheckFormatHandler::HandleInvalidLengthModifier(
  6247. const analyze_format_string::FormatSpecifier &FS,
  6248. const analyze_format_string::ConversionSpecifier &CS,
  6249. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  6250. using namespace analyze_format_string;
  6251. const LengthModifier &LM = FS.getLengthModifier();
  6252. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6253. // See if we know how to fix this length modifier.
  6254. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6255. if (FixedLM) {
  6256. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6257. getLocationOfByte(LM.getStart()),
  6258. /*IsStringLocation*/true,
  6259. getSpecifierRange(startSpecifier, specifierLen));
  6260. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6261. << FixedLM->toString()
  6262. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6263. } else {
  6264. FixItHint Hint;
  6265. if (DiagID == diag::warn_format_nonsensical_length)
  6266. Hint = FixItHint::CreateRemoval(LMRange);
  6267. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  6268. getLocationOfByte(LM.getStart()),
  6269. /*IsStringLocation*/true,
  6270. getSpecifierRange(startSpecifier, specifierLen),
  6271. Hint);
  6272. }
  6273. }
  6274. void CheckFormatHandler::HandleNonStandardLengthModifier(
  6275. const analyze_format_string::FormatSpecifier &FS,
  6276. const char *startSpecifier, unsigned specifierLen) {
  6277. using namespace analyze_format_string;
  6278. const LengthModifier &LM = FS.getLengthModifier();
  6279. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  6280. // See if we know how to fix this length modifier.
  6281. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  6282. if (FixedLM) {
  6283. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6284. << LM.toString() << 0,
  6285. getLocationOfByte(LM.getStart()),
  6286. /*IsStringLocation*/true,
  6287. getSpecifierRange(startSpecifier, specifierLen));
  6288. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  6289. << FixedLM->toString()
  6290. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  6291. } else {
  6292. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6293. << LM.toString() << 0,
  6294. getLocationOfByte(LM.getStart()),
  6295. /*IsStringLocation*/true,
  6296. getSpecifierRange(startSpecifier, specifierLen));
  6297. }
  6298. }
  6299. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  6300. const analyze_format_string::ConversionSpecifier &CS,
  6301. const char *startSpecifier, unsigned specifierLen) {
  6302. using namespace analyze_format_string;
  6303. // See if we know how to fix this conversion specifier.
  6304. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  6305. if (FixedCS) {
  6306. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6307. << CS.toString() << /*conversion specifier*/1,
  6308. getLocationOfByte(CS.getStart()),
  6309. /*IsStringLocation*/true,
  6310. getSpecifierRange(startSpecifier, specifierLen));
  6311. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  6312. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  6313. << FixedCS->toString()
  6314. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  6315. } else {
  6316. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  6317. << CS.toString() << /*conversion specifier*/1,
  6318. getLocationOfByte(CS.getStart()),
  6319. /*IsStringLocation*/true,
  6320. getSpecifierRange(startSpecifier, specifierLen));
  6321. }
  6322. }
  6323. void CheckFormatHandler::HandlePosition(const char *startPos,
  6324. unsigned posLen) {
  6325. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  6326. getLocationOfByte(startPos),
  6327. /*IsStringLocation*/true,
  6328. getSpecifierRange(startPos, posLen));
  6329. }
  6330. void
  6331. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  6332. analyze_format_string::PositionContext p) {
  6333. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  6334. << (unsigned) p,
  6335. getLocationOfByte(startPos), /*IsStringLocation*/true,
  6336. getSpecifierRange(startPos, posLen));
  6337. }
  6338. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  6339. unsigned posLen) {
  6340. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  6341. getLocationOfByte(startPos),
  6342. /*IsStringLocation*/true,
  6343. getSpecifierRange(startPos, posLen));
  6344. }
  6345. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  6346. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  6347. // The presence of a null character is likely an error.
  6348. EmitFormatDiagnostic(
  6349. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  6350. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  6351. getFormatStringRange());
  6352. }
  6353. }
  6354. // Note that this may return NULL if there was an error parsing or building
  6355. // one of the argument expressions.
  6356. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  6357. return Args[FirstDataArg + i];
  6358. }
  6359. void CheckFormatHandler::DoneProcessing() {
  6360. // Does the number of data arguments exceed the number of
  6361. // format conversions in the format string?
  6362. if (!HasVAListArg) {
  6363. // Find any arguments that weren't covered.
  6364. CoveredArgs.flip();
  6365. signed notCoveredArg = CoveredArgs.find_first();
  6366. if (notCoveredArg >= 0) {
  6367. assert((unsigned)notCoveredArg < NumDataArgs);
  6368. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  6369. } else {
  6370. UncoveredArg.setAllCovered();
  6371. }
  6372. }
  6373. }
  6374. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  6375. const Expr *ArgExpr) {
  6376. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  6377. "Invalid state");
  6378. if (!ArgExpr)
  6379. return;
  6380. SourceLocation Loc = ArgExpr->getBeginLoc();
  6381. if (S.getSourceManager().isInSystemMacro(Loc))
  6382. return;
  6383. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  6384. for (auto E : DiagnosticExprs)
  6385. PDiag << E->getSourceRange();
  6386. CheckFormatHandler::EmitFormatDiagnostic(
  6387. S, IsFunctionCall, DiagnosticExprs[0],
  6388. PDiag, Loc, /*IsStringLocation*/false,
  6389. DiagnosticExprs[0]->getSourceRange());
  6390. }
  6391. bool
  6392. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  6393. SourceLocation Loc,
  6394. const char *startSpec,
  6395. unsigned specifierLen,
  6396. const char *csStart,
  6397. unsigned csLen) {
  6398. bool keepGoing = true;
  6399. if (argIndex < NumDataArgs) {
  6400. // Consider the argument coverered, even though the specifier doesn't
  6401. // make sense.
  6402. CoveredArgs.set(argIndex);
  6403. }
  6404. else {
  6405. // If argIndex exceeds the number of data arguments we
  6406. // don't issue a warning because that is just a cascade of warnings (and
  6407. // they may have intended '%%' anyway). We don't want to continue processing
  6408. // the format string after this point, however, as we will like just get
  6409. // gibberish when trying to match arguments.
  6410. keepGoing = false;
  6411. }
  6412. StringRef Specifier(csStart, csLen);
  6413. // If the specifier in non-printable, it could be the first byte of a UTF-8
  6414. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  6415. // hex value.
  6416. std::string CodePointStr;
  6417. if (!llvm::sys::locale::isPrint(*csStart)) {
  6418. llvm::UTF32 CodePoint;
  6419. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  6420. const llvm::UTF8 *E =
  6421. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  6422. llvm::ConversionResult Result =
  6423. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  6424. if (Result != llvm::conversionOK) {
  6425. unsigned char FirstChar = *csStart;
  6426. CodePoint = (llvm::UTF32)FirstChar;
  6427. }
  6428. llvm::raw_string_ostream OS(CodePointStr);
  6429. if (CodePoint < 256)
  6430. OS << "\\x" << llvm::format("%02x", CodePoint);
  6431. else if (CodePoint <= 0xFFFF)
  6432. OS << "\\u" << llvm::format("%04x", CodePoint);
  6433. else
  6434. OS << "\\U" << llvm::format("%08x", CodePoint);
  6435. OS.flush();
  6436. Specifier = CodePointStr;
  6437. }
  6438. EmitFormatDiagnostic(
  6439. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  6440. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  6441. return keepGoing;
  6442. }
  6443. void
  6444. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  6445. const char *startSpec,
  6446. unsigned specifierLen) {
  6447. EmitFormatDiagnostic(
  6448. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  6449. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  6450. }
  6451. bool
  6452. CheckFormatHandler::CheckNumArgs(
  6453. const analyze_format_string::FormatSpecifier &FS,
  6454. const analyze_format_string::ConversionSpecifier &CS,
  6455. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  6456. if (argIndex >= NumDataArgs) {
  6457. PartialDiagnostic PDiag = FS.usesPositionalArg()
  6458. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  6459. << (argIndex+1) << NumDataArgs)
  6460. : S.PDiag(diag::warn_printf_insufficient_data_args);
  6461. EmitFormatDiagnostic(
  6462. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  6463. getSpecifierRange(startSpecifier, specifierLen));
  6464. // Since more arguments than conversion tokens are given, by extension
  6465. // all arguments are covered, so mark this as so.
  6466. UncoveredArg.setAllCovered();
  6467. return false;
  6468. }
  6469. return true;
  6470. }
  6471. template<typename Range>
  6472. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  6473. SourceLocation Loc,
  6474. bool IsStringLocation,
  6475. Range StringRange,
  6476. ArrayRef<FixItHint> FixIt) {
  6477. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  6478. Loc, IsStringLocation, StringRange, FixIt);
  6479. }
  6480. /// If the format string is not within the function call, emit a note
  6481. /// so that the function call and string are in diagnostic messages.
  6482. ///
  6483. /// \param InFunctionCall if true, the format string is within the function
  6484. /// call and only one diagnostic message will be produced. Otherwise, an
  6485. /// extra note will be emitted pointing to location of the format string.
  6486. ///
  6487. /// \param ArgumentExpr the expression that is passed as the format string
  6488. /// argument in the function call. Used for getting locations when two
  6489. /// diagnostics are emitted.
  6490. ///
  6491. /// \param PDiag the callee should already have provided any strings for the
  6492. /// diagnostic message. This function only adds locations and fixits
  6493. /// to diagnostics.
  6494. ///
  6495. /// \param Loc primary location for diagnostic. If two diagnostics are
  6496. /// required, one will be at Loc and a new SourceLocation will be created for
  6497. /// the other one.
  6498. ///
  6499. /// \param IsStringLocation if true, Loc points to the format string should be
  6500. /// used for the note. Otherwise, Loc points to the argument list and will
  6501. /// be used with PDiag.
  6502. ///
  6503. /// \param StringRange some or all of the string to highlight. This is
  6504. /// templated so it can accept either a CharSourceRange or a SourceRange.
  6505. ///
  6506. /// \param FixIt optional fix it hint for the format string.
  6507. template <typename Range>
  6508. void CheckFormatHandler::EmitFormatDiagnostic(
  6509. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  6510. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  6511. Range StringRange, ArrayRef<FixItHint> FixIt) {
  6512. if (InFunctionCall) {
  6513. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  6514. D << StringRange;
  6515. D << FixIt;
  6516. } else {
  6517. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  6518. << ArgumentExpr->getSourceRange();
  6519. const Sema::SemaDiagnosticBuilder &Note =
  6520. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  6521. diag::note_format_string_defined);
  6522. Note << StringRange;
  6523. Note << FixIt;
  6524. }
  6525. }
  6526. //===--- CHECK: Printf format string checking ------------------------------===//
  6527. namespace {
  6528. class CheckPrintfHandler : public CheckFormatHandler {
  6529. public:
  6530. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  6531. const Expr *origFormatExpr,
  6532. const Sema::FormatStringType type, unsigned firstDataArg,
  6533. unsigned numDataArgs, bool isObjC, const char *beg,
  6534. bool hasVAListArg, ArrayRef<const Expr *> Args,
  6535. unsigned formatIdx, bool inFunctionCall,
  6536. Sema::VariadicCallType CallType,
  6537. llvm::SmallBitVector &CheckedVarArgs,
  6538. UncoveredArgHandler &UncoveredArg)
  6539. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  6540. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  6541. inFunctionCall, CallType, CheckedVarArgs,
  6542. UncoveredArg) {}
  6543. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  6544. /// Returns true if '%@' specifiers are allowed in the format string.
  6545. bool allowsObjCArg() const {
  6546. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  6547. FSType == Sema::FST_OSTrace;
  6548. }
  6549. bool HandleInvalidPrintfConversionSpecifier(
  6550. const analyze_printf::PrintfSpecifier &FS,
  6551. const char *startSpecifier,
  6552. unsigned specifierLen) override;
  6553. void handleInvalidMaskType(StringRef MaskType) override;
  6554. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  6555. const char *startSpecifier,
  6556. unsigned specifierLen) override;
  6557. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  6558. const char *StartSpecifier,
  6559. unsigned SpecifierLen,
  6560. const Expr *E);
  6561. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  6562. const char *startSpecifier, unsigned specifierLen);
  6563. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  6564. const analyze_printf::OptionalAmount &Amt,
  6565. unsigned type,
  6566. const char *startSpecifier, unsigned specifierLen);
  6567. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6568. const analyze_printf::OptionalFlag &flag,
  6569. const char *startSpecifier, unsigned specifierLen);
  6570. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  6571. const analyze_printf::OptionalFlag &ignoredFlag,
  6572. const analyze_printf::OptionalFlag &flag,
  6573. const char *startSpecifier, unsigned specifierLen);
  6574. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  6575. const Expr *E);
  6576. void HandleEmptyObjCModifierFlag(const char *startFlag,
  6577. unsigned flagLen) override;
  6578. void HandleInvalidObjCModifierFlag(const char *startFlag,
  6579. unsigned flagLen) override;
  6580. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  6581. const char *flagsEnd,
  6582. const char *conversionPosition)
  6583. override;
  6584. };
  6585. } // namespace
  6586. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  6587. const analyze_printf::PrintfSpecifier &FS,
  6588. const char *startSpecifier,
  6589. unsigned specifierLen) {
  6590. const analyze_printf::PrintfConversionSpecifier &CS =
  6591. FS.getConversionSpecifier();
  6592. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  6593. getLocationOfByte(CS.getStart()),
  6594. startSpecifier, specifierLen,
  6595. CS.getStart(), CS.getLength());
  6596. }
  6597. void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
  6598. S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
  6599. }
  6600. bool CheckPrintfHandler::HandleAmount(
  6601. const analyze_format_string::OptionalAmount &Amt,
  6602. unsigned k, const char *startSpecifier,
  6603. unsigned specifierLen) {
  6604. if (Amt.hasDataArgument()) {
  6605. if (!HasVAListArg) {
  6606. unsigned argIndex = Amt.getArgIndex();
  6607. if (argIndex >= NumDataArgs) {
  6608. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  6609. << k,
  6610. getLocationOfByte(Amt.getStart()),
  6611. /*IsStringLocation*/true,
  6612. getSpecifierRange(startSpecifier, specifierLen));
  6613. // Don't do any more checking. We will just emit
  6614. // spurious errors.
  6615. return false;
  6616. }
  6617. // Type check the data argument. It should be an 'int'.
  6618. // Although not in conformance with C99, we also allow the argument to be
  6619. // an 'unsigned int' as that is a reasonably safe case. GCC also
  6620. // doesn't emit a warning for that case.
  6621. CoveredArgs.set(argIndex);
  6622. const Expr *Arg = getDataArg(argIndex);
  6623. if (!Arg)
  6624. return false;
  6625. QualType T = Arg->getType();
  6626. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  6627. assert(AT.isValid());
  6628. if (!AT.matchesType(S.Context, T)) {
  6629. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  6630. << k << AT.getRepresentativeTypeName(S.Context)
  6631. << T << Arg->getSourceRange(),
  6632. getLocationOfByte(Amt.getStart()),
  6633. /*IsStringLocation*/true,
  6634. getSpecifierRange(startSpecifier, specifierLen));
  6635. // Don't do any more checking. We will just emit
  6636. // spurious errors.
  6637. return false;
  6638. }
  6639. }
  6640. }
  6641. return true;
  6642. }
  6643. void CheckPrintfHandler::HandleInvalidAmount(
  6644. const analyze_printf::PrintfSpecifier &FS,
  6645. const analyze_printf::OptionalAmount &Amt,
  6646. unsigned type,
  6647. const char *startSpecifier,
  6648. unsigned specifierLen) {
  6649. const analyze_printf::PrintfConversionSpecifier &CS =
  6650. FS.getConversionSpecifier();
  6651. FixItHint fixit =
  6652. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  6653. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  6654. Amt.getConstantLength()))
  6655. : FixItHint();
  6656. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  6657. << type << CS.toString(),
  6658. getLocationOfByte(Amt.getStart()),
  6659. /*IsStringLocation*/true,
  6660. getSpecifierRange(startSpecifier, specifierLen),
  6661. fixit);
  6662. }
  6663. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  6664. const analyze_printf::OptionalFlag &flag,
  6665. const char *startSpecifier,
  6666. unsigned specifierLen) {
  6667. // Warn about pointless flag with a fixit removal.
  6668. const analyze_printf::PrintfConversionSpecifier &CS =
  6669. FS.getConversionSpecifier();
  6670. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  6671. << flag.toString() << CS.toString(),
  6672. getLocationOfByte(flag.getPosition()),
  6673. /*IsStringLocation*/true,
  6674. getSpecifierRange(startSpecifier, specifierLen),
  6675. FixItHint::CreateRemoval(
  6676. getSpecifierRange(flag.getPosition(), 1)));
  6677. }
  6678. void CheckPrintfHandler::HandleIgnoredFlag(
  6679. const analyze_printf::PrintfSpecifier &FS,
  6680. const analyze_printf::OptionalFlag &ignoredFlag,
  6681. const analyze_printf::OptionalFlag &flag,
  6682. const char *startSpecifier,
  6683. unsigned specifierLen) {
  6684. // Warn about ignored flag with a fixit removal.
  6685. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  6686. << ignoredFlag.toString() << flag.toString(),
  6687. getLocationOfByte(ignoredFlag.getPosition()),
  6688. /*IsStringLocation*/true,
  6689. getSpecifierRange(startSpecifier, specifierLen),
  6690. FixItHint::CreateRemoval(
  6691. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  6692. }
  6693. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  6694. unsigned flagLen) {
  6695. // Warn about an empty flag.
  6696. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  6697. getLocationOfByte(startFlag),
  6698. /*IsStringLocation*/true,
  6699. getSpecifierRange(startFlag, flagLen));
  6700. }
  6701. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  6702. unsigned flagLen) {
  6703. // Warn about an invalid flag.
  6704. auto Range = getSpecifierRange(startFlag, flagLen);
  6705. StringRef flag(startFlag, flagLen);
  6706. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  6707. getLocationOfByte(startFlag),
  6708. /*IsStringLocation*/true,
  6709. Range, FixItHint::CreateRemoval(Range));
  6710. }
  6711. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  6712. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  6713. // Warn about using '[...]' without a '@' conversion.
  6714. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  6715. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  6716. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  6717. getLocationOfByte(conversionPosition),
  6718. /*IsStringLocation*/true,
  6719. Range, FixItHint::CreateRemoval(Range));
  6720. }
  6721. // Determines if the specified is a C++ class or struct containing
  6722. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  6723. // "c_str()").
  6724. template<typename MemberKind>
  6725. static llvm::SmallPtrSet<MemberKind*, 1>
  6726. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  6727. const RecordType *RT = Ty->getAs<RecordType>();
  6728. llvm::SmallPtrSet<MemberKind*, 1> Results;
  6729. if (!RT)
  6730. return Results;
  6731. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  6732. if (!RD || !RD->getDefinition())
  6733. return Results;
  6734. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  6735. Sema::LookupMemberName);
  6736. R.suppressDiagnostics();
  6737. // We just need to include all members of the right kind turned up by the
  6738. // filter, at this point.
  6739. if (S.LookupQualifiedName(R, RT->getDecl()))
  6740. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6741. NamedDecl *decl = (*I)->getUnderlyingDecl();
  6742. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  6743. Results.insert(FK);
  6744. }
  6745. return Results;
  6746. }
  6747. /// Check if we could call '.c_str()' on an object.
  6748. ///
  6749. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  6750. /// allow the call, or if it would be ambiguous).
  6751. bool Sema::hasCStrMethod(const Expr *E) {
  6752. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6753. MethodSet Results =
  6754. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  6755. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6756. MI != ME; ++MI)
  6757. if ((*MI)->getMinRequiredArguments() == 0)
  6758. return true;
  6759. return false;
  6760. }
  6761. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  6762. // better diagnostic if so. AT is assumed to be valid.
  6763. // Returns true when a c_str() conversion method is found.
  6764. bool CheckPrintfHandler::checkForCStrMembers(
  6765. const analyze_printf::ArgType &AT, const Expr *E) {
  6766. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  6767. MethodSet Results =
  6768. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  6769. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  6770. MI != ME; ++MI) {
  6771. const CXXMethodDecl *Method = *MI;
  6772. if (Method->getMinRequiredArguments() == 0 &&
  6773. AT.matchesType(S.Context, Method->getReturnType())) {
  6774. // FIXME: Suggest parens if the expression needs them.
  6775. SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
  6776. S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
  6777. << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  6778. return true;
  6779. }
  6780. }
  6781. return false;
  6782. }
  6783. bool
  6784. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  6785. &FS,
  6786. const char *startSpecifier,
  6787. unsigned specifierLen) {
  6788. using namespace analyze_format_string;
  6789. using namespace analyze_printf;
  6790. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  6791. if (FS.consumesDataArgument()) {
  6792. if (atFirstArg) {
  6793. atFirstArg = false;
  6794. usesPositionalArgs = FS.usesPositionalArg();
  6795. }
  6796. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  6797. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  6798. startSpecifier, specifierLen);
  6799. return false;
  6800. }
  6801. }
  6802. // First check if the field width, precision, and conversion specifier
  6803. // have matching data arguments.
  6804. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  6805. startSpecifier, specifierLen)) {
  6806. return false;
  6807. }
  6808. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  6809. startSpecifier, specifierLen)) {
  6810. return false;
  6811. }
  6812. if (!CS.consumesDataArgument()) {
  6813. // FIXME: Technically specifying a precision or field width here
  6814. // makes no sense. Worth issuing a warning at some point.
  6815. return true;
  6816. }
  6817. // Consume the argument.
  6818. unsigned argIndex = FS.getArgIndex();
  6819. if (argIndex < NumDataArgs) {
  6820. // The check to see if the argIndex is valid will come later.
  6821. // We set the bit here because we may exit early from this
  6822. // function if we encounter some other error.
  6823. CoveredArgs.set(argIndex);
  6824. }
  6825. // FreeBSD kernel extensions.
  6826. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  6827. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  6828. // We need at least two arguments.
  6829. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  6830. return false;
  6831. // Claim the second argument.
  6832. CoveredArgs.set(argIndex + 1);
  6833. // Type check the first argument (int for %b, pointer for %D)
  6834. const Expr *Ex = getDataArg(argIndex);
  6835. const analyze_printf::ArgType &AT =
  6836. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  6837. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  6838. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  6839. EmitFormatDiagnostic(
  6840. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6841. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  6842. << false << Ex->getSourceRange(),
  6843. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  6844. getSpecifierRange(startSpecifier, specifierLen));
  6845. // Type check the second argument (char * for both %b and %D)
  6846. Ex = getDataArg(argIndex + 1);
  6847. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  6848. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  6849. EmitFormatDiagnostic(
  6850. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  6851. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  6852. << false << Ex->getSourceRange(),
  6853. Ex->getBeginLoc(), /*IsStringLocation*/ false,
  6854. getSpecifierRange(startSpecifier, specifierLen));
  6855. return true;
  6856. }
  6857. // Check for using an Objective-C specific conversion specifier
  6858. // in a non-ObjC literal.
  6859. if (!allowsObjCArg() && CS.isObjCArg()) {
  6860. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6861. specifierLen);
  6862. }
  6863. // %P can only be used with os_log.
  6864. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  6865. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6866. specifierLen);
  6867. }
  6868. // %n is not allowed with os_log.
  6869. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  6870. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  6871. getLocationOfByte(CS.getStart()),
  6872. /*IsStringLocation*/ false,
  6873. getSpecifierRange(startSpecifier, specifierLen));
  6874. return true;
  6875. }
  6876. // Only scalars are allowed for os_trace.
  6877. if (FSType == Sema::FST_OSTrace &&
  6878. (CS.getKind() == ConversionSpecifier::PArg ||
  6879. CS.getKind() == ConversionSpecifier::sArg ||
  6880. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  6881. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  6882. specifierLen);
  6883. }
  6884. // Check for use of public/private annotation outside of os_log().
  6885. if (FSType != Sema::FST_OSLog) {
  6886. if (FS.isPublic().isSet()) {
  6887. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6888. << "public",
  6889. getLocationOfByte(FS.isPublic().getPosition()),
  6890. /*IsStringLocation*/ false,
  6891. getSpecifierRange(startSpecifier, specifierLen));
  6892. }
  6893. if (FS.isPrivate().isSet()) {
  6894. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  6895. << "private",
  6896. getLocationOfByte(FS.isPrivate().getPosition()),
  6897. /*IsStringLocation*/ false,
  6898. getSpecifierRange(startSpecifier, specifierLen));
  6899. }
  6900. }
  6901. // Check for invalid use of field width
  6902. if (!FS.hasValidFieldWidth()) {
  6903. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  6904. startSpecifier, specifierLen);
  6905. }
  6906. // Check for invalid use of precision
  6907. if (!FS.hasValidPrecision()) {
  6908. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  6909. startSpecifier, specifierLen);
  6910. }
  6911. // Precision is mandatory for %P specifier.
  6912. if (CS.getKind() == ConversionSpecifier::PArg &&
  6913. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  6914. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  6915. getLocationOfByte(startSpecifier),
  6916. /*IsStringLocation*/ false,
  6917. getSpecifierRange(startSpecifier, specifierLen));
  6918. }
  6919. // Check each flag does not conflict with any other component.
  6920. if (!FS.hasValidThousandsGroupingPrefix())
  6921. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  6922. if (!FS.hasValidLeadingZeros())
  6923. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  6924. if (!FS.hasValidPlusPrefix())
  6925. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  6926. if (!FS.hasValidSpacePrefix())
  6927. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  6928. if (!FS.hasValidAlternativeForm())
  6929. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  6930. if (!FS.hasValidLeftJustified())
  6931. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  6932. // Check that flags are not ignored by another flag
  6933. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  6934. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  6935. startSpecifier, specifierLen);
  6936. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  6937. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  6938. startSpecifier, specifierLen);
  6939. // Check the length modifier is valid with the given conversion specifier.
  6940. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  6941. S.getLangOpts()))
  6942. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6943. diag::warn_format_nonsensical_length);
  6944. else if (!FS.hasStandardLengthModifier())
  6945. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  6946. else if (!FS.hasStandardLengthConversionCombination())
  6947. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  6948. diag::warn_format_non_standard_conversion_spec);
  6949. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  6950. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  6951. // The remaining checks depend on the data arguments.
  6952. if (HasVAListArg)
  6953. return true;
  6954. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  6955. return false;
  6956. const Expr *Arg = getDataArg(argIndex);
  6957. if (!Arg)
  6958. return true;
  6959. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  6960. }
  6961. static bool requiresParensToAddCast(const Expr *E) {
  6962. // FIXME: We should have a general way to reason about operator
  6963. // precedence and whether parens are actually needed here.
  6964. // Take care of a few common cases where they aren't.
  6965. const Expr *Inside = E->IgnoreImpCasts();
  6966. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  6967. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  6968. switch (Inside->getStmtClass()) {
  6969. case Stmt::ArraySubscriptExprClass:
  6970. case Stmt::CallExprClass:
  6971. case Stmt::CharacterLiteralClass:
  6972. case Stmt::CXXBoolLiteralExprClass:
  6973. case Stmt::DeclRefExprClass:
  6974. case Stmt::FloatingLiteralClass:
  6975. case Stmt::IntegerLiteralClass:
  6976. case Stmt::MemberExprClass:
  6977. case Stmt::ObjCArrayLiteralClass:
  6978. case Stmt::ObjCBoolLiteralExprClass:
  6979. case Stmt::ObjCBoxedExprClass:
  6980. case Stmt::ObjCDictionaryLiteralClass:
  6981. case Stmt::ObjCEncodeExprClass:
  6982. case Stmt::ObjCIvarRefExprClass:
  6983. case Stmt::ObjCMessageExprClass:
  6984. case Stmt::ObjCPropertyRefExprClass:
  6985. case Stmt::ObjCStringLiteralClass:
  6986. case Stmt::ObjCSubscriptRefExprClass:
  6987. case Stmt::ParenExprClass:
  6988. case Stmt::StringLiteralClass:
  6989. case Stmt::UnaryOperatorClass:
  6990. return false;
  6991. default:
  6992. return true;
  6993. }
  6994. }
  6995. static std::pair<QualType, StringRef>
  6996. shouldNotPrintDirectly(const ASTContext &Context,
  6997. QualType IntendedTy,
  6998. const Expr *E) {
  6999. // Use a 'while' to peel off layers of typedefs.
  7000. QualType TyTy = IntendedTy;
  7001. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  7002. StringRef Name = UserTy->getDecl()->getName();
  7003. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  7004. .Case("CFIndex", Context.getNSIntegerType())
  7005. .Case("NSInteger", Context.getNSIntegerType())
  7006. .Case("NSUInteger", Context.getNSUIntegerType())
  7007. .Case("SInt32", Context.IntTy)
  7008. .Case("UInt32", Context.UnsignedIntTy)
  7009. .Default(QualType());
  7010. if (!CastTy.isNull())
  7011. return std::make_pair(CastTy, Name);
  7012. TyTy = UserTy->desugar();
  7013. }
  7014. // Strip parens if necessary.
  7015. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  7016. return shouldNotPrintDirectly(Context,
  7017. PE->getSubExpr()->getType(),
  7018. PE->getSubExpr());
  7019. // If this is a conditional expression, then its result type is constructed
  7020. // via usual arithmetic conversions and thus there might be no necessary
  7021. // typedef sugar there. Recurse to operands to check for NSInteger &
  7022. // Co. usage condition.
  7023. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7024. QualType TrueTy, FalseTy;
  7025. StringRef TrueName, FalseName;
  7026. std::tie(TrueTy, TrueName) =
  7027. shouldNotPrintDirectly(Context,
  7028. CO->getTrueExpr()->getType(),
  7029. CO->getTrueExpr());
  7030. std::tie(FalseTy, FalseName) =
  7031. shouldNotPrintDirectly(Context,
  7032. CO->getFalseExpr()->getType(),
  7033. CO->getFalseExpr());
  7034. if (TrueTy == FalseTy)
  7035. return std::make_pair(TrueTy, TrueName);
  7036. else if (TrueTy.isNull())
  7037. return std::make_pair(FalseTy, FalseName);
  7038. else if (FalseTy.isNull())
  7039. return std::make_pair(TrueTy, TrueName);
  7040. }
  7041. return std::make_pair(QualType(), StringRef());
  7042. }
  7043. /// Return true if \p ICE is an implicit argument promotion of an arithmetic
  7044. /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
  7045. /// type do not count.
  7046. static bool
  7047. isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
  7048. QualType From = ICE->getSubExpr()->getType();
  7049. QualType To = ICE->getType();
  7050. // It's an integer promotion if the destination type is the promoted
  7051. // source type.
  7052. if (ICE->getCastKind() == CK_IntegralCast &&
  7053. From->isPromotableIntegerType() &&
  7054. S.Context.getPromotedIntegerType(From) == To)
  7055. return true;
  7056. // Look through vector types, since we do default argument promotion for
  7057. // those in OpenCL.
  7058. if (const auto *VecTy = From->getAs<ExtVectorType>())
  7059. From = VecTy->getElementType();
  7060. if (const auto *VecTy = To->getAs<ExtVectorType>())
  7061. To = VecTy->getElementType();
  7062. // It's a floating promotion if the source type is a lower rank.
  7063. return ICE->getCastKind() == CK_FloatingCast &&
  7064. S.Context.getFloatingTypeOrder(From, To) < 0;
  7065. }
  7066. bool
  7067. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  7068. const char *StartSpecifier,
  7069. unsigned SpecifierLen,
  7070. const Expr *E) {
  7071. using namespace analyze_format_string;
  7072. using namespace analyze_printf;
  7073. // Now type check the data expression that matches the
  7074. // format specifier.
  7075. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  7076. if (!AT.isValid())
  7077. return true;
  7078. QualType ExprTy = E->getType();
  7079. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  7080. ExprTy = TET->getUnderlyingExpr()->getType();
  7081. }
  7082. const analyze_printf::ArgType::MatchKind Match =
  7083. AT.matchesType(S.Context, ExprTy);
  7084. bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
  7085. if (Match == analyze_printf::ArgType::Match)
  7086. return true;
  7087. // Look through argument promotions for our error message's reported type.
  7088. // This includes the integral and floating promotions, but excludes array
  7089. // and function pointer decay (seeing that an argument intended to be a
  7090. // string has type 'char [6]' is probably more confusing than 'char *') and
  7091. // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
  7092. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7093. if (isArithmeticArgumentPromotion(S, ICE)) {
  7094. E = ICE->getSubExpr();
  7095. ExprTy = E->getType();
  7096. // Check if we didn't match because of an implicit cast from a 'char'
  7097. // or 'short' to an 'int'. This is done because printf is a varargs
  7098. // function.
  7099. if (ICE->getType() == S.Context.IntTy ||
  7100. ICE->getType() == S.Context.UnsignedIntTy) {
  7101. // All further checking is done on the subexpression.
  7102. if (AT.matchesType(S.Context, ExprTy))
  7103. return true;
  7104. }
  7105. }
  7106. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  7107. // Special case for 'a', which has type 'int' in C.
  7108. // Note, however, that we do /not/ want to treat multibyte constants like
  7109. // 'MooV' as characters! This form is deprecated but still exists.
  7110. if (ExprTy == S.Context.IntTy)
  7111. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  7112. ExprTy = S.Context.CharTy;
  7113. }
  7114. // Look through enums to their underlying type.
  7115. bool IsEnum = false;
  7116. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  7117. ExprTy = EnumTy->getDecl()->getIntegerType();
  7118. IsEnum = true;
  7119. }
  7120. // %C in an Objective-C context prints a unichar, not a wchar_t.
  7121. // If the argument is an integer of some kind, believe the %C and suggest
  7122. // a cast instead of changing the conversion specifier.
  7123. QualType IntendedTy = ExprTy;
  7124. if (isObjCContext() &&
  7125. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  7126. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  7127. !ExprTy->isCharType()) {
  7128. // 'unichar' is defined as a typedef of unsigned short, but we should
  7129. // prefer using the typedef if it is visible.
  7130. IntendedTy = S.Context.UnsignedShortTy;
  7131. // While we are here, check if the value is an IntegerLiteral that happens
  7132. // to be within the valid range.
  7133. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  7134. const llvm::APInt &V = IL->getValue();
  7135. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  7136. return true;
  7137. }
  7138. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
  7139. Sema::LookupOrdinaryName);
  7140. if (S.LookupName(Result, S.getCurScope())) {
  7141. NamedDecl *ND = Result.getFoundDecl();
  7142. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  7143. if (TD->getUnderlyingType() == IntendedTy)
  7144. IntendedTy = S.Context.getTypedefType(TD);
  7145. }
  7146. }
  7147. }
  7148. // Special-case some of Darwin's platform-independence types by suggesting
  7149. // casts to primitive types that are known to be large enough.
  7150. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  7151. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  7152. QualType CastTy;
  7153. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  7154. if (!CastTy.isNull()) {
  7155. // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
  7156. // (long in ASTContext). Only complain to pedants.
  7157. if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
  7158. (AT.isSizeT() || AT.isPtrdiffT()) &&
  7159. AT.matchesType(S.Context, CastTy))
  7160. Pedantic = true;
  7161. IntendedTy = CastTy;
  7162. ShouldNotPrintDirectly = true;
  7163. }
  7164. }
  7165. // We may be able to offer a FixItHint if it is a supported type.
  7166. PrintfSpecifier fixedFS = FS;
  7167. bool Success =
  7168. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  7169. if (Success) {
  7170. // Get the fix string from the fixed format specifier
  7171. SmallString<16> buf;
  7172. llvm::raw_svector_ostream os(buf);
  7173. fixedFS.toString(os);
  7174. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  7175. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  7176. unsigned Diag =
  7177. Pedantic
  7178. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7179. : diag::warn_format_conversion_argument_type_mismatch;
  7180. // In this case, the specifier is wrong and should be changed to match
  7181. // the argument.
  7182. EmitFormatDiagnostic(S.PDiag(Diag)
  7183. << AT.getRepresentativeTypeName(S.Context)
  7184. << IntendedTy << IsEnum << E->getSourceRange(),
  7185. E->getBeginLoc(),
  7186. /*IsStringLocation*/ false, SpecRange,
  7187. FixItHint::CreateReplacement(SpecRange, os.str()));
  7188. } else {
  7189. // The canonical type for formatting this value is different from the
  7190. // actual type of the expression. (This occurs, for example, with Darwin's
  7191. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  7192. // should be printed as 'long' for 64-bit compatibility.)
  7193. // Rather than emitting a normal format/argument mismatch, we want to
  7194. // add a cast to the recommended type (and correct the format string
  7195. // if necessary).
  7196. SmallString<16> CastBuf;
  7197. llvm::raw_svector_ostream CastFix(CastBuf);
  7198. CastFix << "(";
  7199. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  7200. CastFix << ")";
  7201. SmallVector<FixItHint,4> Hints;
  7202. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  7203. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  7204. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  7205. // If there's already a cast present, just replace it.
  7206. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  7207. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  7208. } else if (!requiresParensToAddCast(E)) {
  7209. // If the expression has high enough precedence,
  7210. // just write the C-style cast.
  7211. Hints.push_back(
  7212. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7213. } else {
  7214. // Otherwise, add parens around the expression as well as the cast.
  7215. CastFix << "(";
  7216. Hints.push_back(
  7217. FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
  7218. SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
  7219. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  7220. }
  7221. if (ShouldNotPrintDirectly) {
  7222. // The expression has a type that should not be printed directly.
  7223. // We extract the name from the typedef because we don't want to show
  7224. // the underlying type in the diagnostic.
  7225. StringRef Name;
  7226. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  7227. Name = TypedefTy->getDecl()->getName();
  7228. else
  7229. Name = CastTyName;
  7230. unsigned Diag = Pedantic
  7231. ? diag::warn_format_argument_needs_cast_pedantic
  7232. : diag::warn_format_argument_needs_cast;
  7233. EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
  7234. << E->getSourceRange(),
  7235. E->getBeginLoc(), /*IsStringLocation=*/false,
  7236. SpecRange, Hints);
  7237. } else {
  7238. // In this case, the expression could be printed using a different
  7239. // specifier, but we've decided that the specifier is probably correct
  7240. // and we should cast instead. Just use the normal warning message.
  7241. EmitFormatDiagnostic(
  7242. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  7243. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  7244. << E->getSourceRange(),
  7245. E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
  7246. }
  7247. }
  7248. } else {
  7249. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  7250. SpecifierLen);
  7251. // Since the warning for passing non-POD types to variadic functions
  7252. // was deferred until now, we emit a warning for non-POD
  7253. // arguments here.
  7254. switch (S.isValidVarArgType(ExprTy)) {
  7255. case Sema::VAK_Valid:
  7256. case Sema::VAK_ValidInCXX11: {
  7257. unsigned Diag =
  7258. Pedantic
  7259. ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7260. : diag::warn_format_conversion_argument_type_mismatch;
  7261. EmitFormatDiagnostic(
  7262. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  7263. << IsEnum << CSR << E->getSourceRange(),
  7264. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7265. break;
  7266. }
  7267. case Sema::VAK_Undefined:
  7268. case Sema::VAK_MSVCUndefined:
  7269. EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  7270. << S.getLangOpts().CPlusPlus11 << ExprTy
  7271. << CallType
  7272. << AT.getRepresentativeTypeName(S.Context) << CSR
  7273. << E->getSourceRange(),
  7274. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7275. checkForCStrMembers(AT, E);
  7276. break;
  7277. case Sema::VAK_Invalid:
  7278. if (ExprTy->isObjCObjectType())
  7279. EmitFormatDiagnostic(
  7280. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  7281. << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
  7282. << AT.getRepresentativeTypeName(S.Context) << CSR
  7283. << E->getSourceRange(),
  7284. E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
  7285. else
  7286. // FIXME: If this is an initializer list, suggest removing the braces
  7287. // or inserting a cast to the target type.
  7288. S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
  7289. << isa<InitListExpr>(E) << ExprTy << CallType
  7290. << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
  7291. break;
  7292. }
  7293. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  7294. "format string specifier index out of range");
  7295. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  7296. }
  7297. return true;
  7298. }
  7299. //===--- CHECK: Scanf format string checking ------------------------------===//
  7300. namespace {
  7301. class CheckScanfHandler : public CheckFormatHandler {
  7302. public:
  7303. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  7304. const Expr *origFormatExpr, Sema::FormatStringType type,
  7305. unsigned firstDataArg, unsigned numDataArgs,
  7306. const char *beg, bool hasVAListArg,
  7307. ArrayRef<const Expr *> Args, unsigned formatIdx,
  7308. bool inFunctionCall, Sema::VariadicCallType CallType,
  7309. llvm::SmallBitVector &CheckedVarArgs,
  7310. UncoveredArgHandler &UncoveredArg)
  7311. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  7312. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  7313. inFunctionCall, CallType, CheckedVarArgs,
  7314. UncoveredArg) {}
  7315. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  7316. const char *startSpecifier,
  7317. unsigned specifierLen) override;
  7318. bool HandleInvalidScanfConversionSpecifier(
  7319. const analyze_scanf::ScanfSpecifier &FS,
  7320. const char *startSpecifier,
  7321. unsigned specifierLen) override;
  7322. void HandleIncompleteScanList(const char *start, const char *end) override;
  7323. };
  7324. } // namespace
  7325. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  7326. const char *end) {
  7327. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  7328. getLocationOfByte(end), /*IsStringLocation*/true,
  7329. getSpecifierRange(start, end - start));
  7330. }
  7331. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  7332. const analyze_scanf::ScanfSpecifier &FS,
  7333. const char *startSpecifier,
  7334. unsigned specifierLen) {
  7335. const analyze_scanf::ScanfConversionSpecifier &CS =
  7336. FS.getConversionSpecifier();
  7337. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  7338. getLocationOfByte(CS.getStart()),
  7339. startSpecifier, specifierLen,
  7340. CS.getStart(), CS.getLength());
  7341. }
  7342. bool CheckScanfHandler::HandleScanfSpecifier(
  7343. const analyze_scanf::ScanfSpecifier &FS,
  7344. const char *startSpecifier,
  7345. unsigned specifierLen) {
  7346. using namespace analyze_scanf;
  7347. using namespace analyze_format_string;
  7348. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  7349. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  7350. // be used to decide if we are using positional arguments consistently.
  7351. if (FS.consumesDataArgument()) {
  7352. if (atFirstArg) {
  7353. atFirstArg = false;
  7354. usesPositionalArgs = FS.usesPositionalArg();
  7355. }
  7356. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  7357. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  7358. startSpecifier, specifierLen);
  7359. return false;
  7360. }
  7361. }
  7362. // Check if the field with is non-zero.
  7363. const OptionalAmount &Amt = FS.getFieldWidth();
  7364. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  7365. if (Amt.getConstantAmount() == 0) {
  7366. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  7367. Amt.getConstantLength());
  7368. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  7369. getLocationOfByte(Amt.getStart()),
  7370. /*IsStringLocation*/true, R,
  7371. FixItHint::CreateRemoval(R));
  7372. }
  7373. }
  7374. if (!FS.consumesDataArgument()) {
  7375. // FIXME: Technically specifying a precision or field width here
  7376. // makes no sense. Worth issuing a warning at some point.
  7377. return true;
  7378. }
  7379. // Consume the argument.
  7380. unsigned argIndex = FS.getArgIndex();
  7381. if (argIndex < NumDataArgs) {
  7382. // The check to see if the argIndex is valid will come later.
  7383. // We set the bit here because we may exit early from this
  7384. // function if we encounter some other error.
  7385. CoveredArgs.set(argIndex);
  7386. }
  7387. // Check the length modifier is valid with the given conversion specifier.
  7388. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
  7389. S.getLangOpts()))
  7390. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7391. diag::warn_format_nonsensical_length);
  7392. else if (!FS.hasStandardLengthModifier())
  7393. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  7394. else if (!FS.hasStandardLengthConversionCombination())
  7395. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  7396. diag::warn_format_non_standard_conversion_spec);
  7397. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  7398. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  7399. // The remaining checks depend on the data arguments.
  7400. if (HasVAListArg)
  7401. return true;
  7402. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  7403. return false;
  7404. // Check that the argument type matches the format specifier.
  7405. const Expr *Ex = getDataArg(argIndex);
  7406. if (!Ex)
  7407. return true;
  7408. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  7409. if (!AT.isValid()) {
  7410. return true;
  7411. }
  7412. analyze_format_string::ArgType::MatchKind Match =
  7413. AT.matchesType(S.Context, Ex->getType());
  7414. bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
  7415. if (Match == analyze_format_string::ArgType::Match)
  7416. return true;
  7417. ScanfSpecifier fixedFS = FS;
  7418. bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  7419. S.getLangOpts(), S.Context);
  7420. unsigned Diag =
  7421. Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
  7422. : diag::warn_format_conversion_argument_type_mismatch;
  7423. if (Success) {
  7424. // Get the fix string from the fixed format specifier.
  7425. SmallString<128> buf;
  7426. llvm::raw_svector_ostream os(buf);
  7427. fixedFS.toString(os);
  7428. EmitFormatDiagnostic(
  7429. S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
  7430. << Ex->getType() << false << Ex->getSourceRange(),
  7431. Ex->getBeginLoc(),
  7432. /*IsStringLocation*/ false,
  7433. getSpecifierRange(startSpecifier, specifierLen),
  7434. FixItHint::CreateReplacement(
  7435. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  7436. } else {
  7437. EmitFormatDiagnostic(S.PDiag(Diag)
  7438. << AT.getRepresentativeTypeName(S.Context)
  7439. << Ex->getType() << false << Ex->getSourceRange(),
  7440. Ex->getBeginLoc(),
  7441. /*IsStringLocation*/ false,
  7442. getSpecifierRange(startSpecifier, specifierLen));
  7443. }
  7444. return true;
  7445. }
  7446. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  7447. const Expr *OrigFormatExpr,
  7448. ArrayRef<const Expr *> Args,
  7449. bool HasVAListArg, unsigned format_idx,
  7450. unsigned firstDataArg,
  7451. Sema::FormatStringType Type,
  7452. bool inFunctionCall,
  7453. Sema::VariadicCallType CallType,
  7454. llvm::SmallBitVector &CheckedVarArgs,
  7455. UncoveredArgHandler &UncoveredArg) {
  7456. // CHECK: is the format string a wide literal?
  7457. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  7458. CheckFormatHandler::EmitFormatDiagnostic(
  7459. S, inFunctionCall, Args[format_idx],
  7460. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
  7461. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7462. return;
  7463. }
  7464. // Str - The format string. NOTE: this is NOT null-terminated!
  7465. StringRef StrRef = FExpr->getString();
  7466. const char *Str = StrRef.data();
  7467. // Account for cases where the string literal is truncated in a declaration.
  7468. const ConstantArrayType *T =
  7469. S.Context.getAsConstantArrayType(FExpr->getType());
  7470. assert(T && "String literal not of constant array type!");
  7471. size_t TypeSize = T->getSize().getZExtValue();
  7472. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7473. const unsigned numDataArgs = Args.size() - firstDataArg;
  7474. // Emit a warning if the string literal is truncated and does not contain an
  7475. // embedded null character.
  7476. if (TypeSize <= StrRef.size() &&
  7477. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  7478. CheckFormatHandler::EmitFormatDiagnostic(
  7479. S, inFunctionCall, Args[format_idx],
  7480. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  7481. FExpr->getBeginLoc(),
  7482. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  7483. return;
  7484. }
  7485. // CHECK: empty format string?
  7486. if (StrLen == 0 && numDataArgs > 0) {
  7487. CheckFormatHandler::EmitFormatDiagnostic(
  7488. S, inFunctionCall, Args[format_idx],
  7489. S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
  7490. /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
  7491. return;
  7492. }
  7493. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  7494. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  7495. Type == Sema::FST_OSTrace) {
  7496. CheckPrintfHandler H(
  7497. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  7498. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  7499. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  7500. CheckedVarArgs, UncoveredArg);
  7501. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  7502. S.getLangOpts(),
  7503. S.Context.getTargetInfo(),
  7504. Type == Sema::FST_FreeBSDKPrintf))
  7505. H.DoneProcessing();
  7506. } else if (Type == Sema::FST_Scanf) {
  7507. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  7508. numDataArgs, Str, HasVAListArg, Args, format_idx,
  7509. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  7510. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  7511. S.getLangOpts(),
  7512. S.Context.getTargetInfo()))
  7513. H.DoneProcessing();
  7514. } // TODO: handle other formats
  7515. }
  7516. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  7517. // Str - The format string. NOTE: this is NOT null-terminated!
  7518. StringRef StrRef = FExpr->getString();
  7519. const char *Str = StrRef.data();
  7520. // Account for cases where the string literal is truncated in a declaration.
  7521. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  7522. assert(T && "String literal not of constant array type!");
  7523. size_t TypeSize = T->getSize().getZExtValue();
  7524. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  7525. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  7526. getLangOpts(),
  7527. Context.getTargetInfo());
  7528. }
  7529. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  7530. // Returns the related absolute value function that is larger, of 0 if one
  7531. // does not exist.
  7532. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  7533. switch (AbsFunction) {
  7534. default:
  7535. return 0;
  7536. case Builtin::BI__builtin_abs:
  7537. return Builtin::BI__builtin_labs;
  7538. case Builtin::BI__builtin_labs:
  7539. return Builtin::BI__builtin_llabs;
  7540. case Builtin::BI__builtin_llabs:
  7541. return 0;
  7542. case Builtin::BI__builtin_fabsf:
  7543. return Builtin::BI__builtin_fabs;
  7544. case Builtin::BI__builtin_fabs:
  7545. return Builtin::BI__builtin_fabsl;
  7546. case Builtin::BI__builtin_fabsl:
  7547. return 0;
  7548. case Builtin::BI__builtin_cabsf:
  7549. return Builtin::BI__builtin_cabs;
  7550. case Builtin::BI__builtin_cabs:
  7551. return Builtin::BI__builtin_cabsl;
  7552. case Builtin::BI__builtin_cabsl:
  7553. return 0;
  7554. case Builtin::BIabs:
  7555. return Builtin::BIlabs;
  7556. case Builtin::BIlabs:
  7557. return Builtin::BIllabs;
  7558. case Builtin::BIllabs:
  7559. return 0;
  7560. case Builtin::BIfabsf:
  7561. return Builtin::BIfabs;
  7562. case Builtin::BIfabs:
  7563. return Builtin::BIfabsl;
  7564. case Builtin::BIfabsl:
  7565. return 0;
  7566. case Builtin::BIcabsf:
  7567. return Builtin::BIcabs;
  7568. case Builtin::BIcabs:
  7569. return Builtin::BIcabsl;
  7570. case Builtin::BIcabsl:
  7571. return 0;
  7572. }
  7573. }
  7574. // Returns the argument type of the absolute value function.
  7575. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  7576. unsigned AbsType) {
  7577. if (AbsType == 0)
  7578. return QualType();
  7579. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  7580. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  7581. if (Error != ASTContext::GE_None)
  7582. return QualType();
  7583. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  7584. if (!FT)
  7585. return QualType();
  7586. if (FT->getNumParams() != 1)
  7587. return QualType();
  7588. return FT->getParamType(0);
  7589. }
  7590. // Returns the best absolute value function, or zero, based on type and
  7591. // current absolute value function.
  7592. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  7593. unsigned AbsFunctionKind) {
  7594. unsigned BestKind = 0;
  7595. uint64_t ArgSize = Context.getTypeSize(ArgType);
  7596. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  7597. Kind = getLargerAbsoluteValueFunction(Kind)) {
  7598. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  7599. if (Context.getTypeSize(ParamType) >= ArgSize) {
  7600. if (BestKind == 0)
  7601. BestKind = Kind;
  7602. else if (Context.hasSameType(ParamType, ArgType)) {
  7603. BestKind = Kind;
  7604. break;
  7605. }
  7606. }
  7607. }
  7608. return BestKind;
  7609. }
  7610. enum AbsoluteValueKind {
  7611. AVK_Integer,
  7612. AVK_Floating,
  7613. AVK_Complex
  7614. };
  7615. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  7616. if (T->isIntegralOrEnumerationType())
  7617. return AVK_Integer;
  7618. if (T->isRealFloatingType())
  7619. return AVK_Floating;
  7620. if (T->isAnyComplexType())
  7621. return AVK_Complex;
  7622. llvm_unreachable("Type not integer, floating, or complex");
  7623. }
  7624. // Changes the absolute value function to a different type. Preserves whether
  7625. // the function is a builtin.
  7626. static unsigned changeAbsFunction(unsigned AbsKind,
  7627. AbsoluteValueKind ValueKind) {
  7628. switch (ValueKind) {
  7629. case AVK_Integer:
  7630. switch (AbsKind) {
  7631. default:
  7632. return 0;
  7633. case Builtin::BI__builtin_fabsf:
  7634. case Builtin::BI__builtin_fabs:
  7635. case Builtin::BI__builtin_fabsl:
  7636. case Builtin::BI__builtin_cabsf:
  7637. case Builtin::BI__builtin_cabs:
  7638. case Builtin::BI__builtin_cabsl:
  7639. return Builtin::BI__builtin_abs;
  7640. case Builtin::BIfabsf:
  7641. case Builtin::BIfabs:
  7642. case Builtin::BIfabsl:
  7643. case Builtin::BIcabsf:
  7644. case Builtin::BIcabs:
  7645. case Builtin::BIcabsl:
  7646. return Builtin::BIabs;
  7647. }
  7648. case AVK_Floating:
  7649. switch (AbsKind) {
  7650. default:
  7651. return 0;
  7652. case Builtin::BI__builtin_abs:
  7653. case Builtin::BI__builtin_labs:
  7654. case Builtin::BI__builtin_llabs:
  7655. case Builtin::BI__builtin_cabsf:
  7656. case Builtin::BI__builtin_cabs:
  7657. case Builtin::BI__builtin_cabsl:
  7658. return Builtin::BI__builtin_fabsf;
  7659. case Builtin::BIabs:
  7660. case Builtin::BIlabs:
  7661. case Builtin::BIllabs:
  7662. case Builtin::BIcabsf:
  7663. case Builtin::BIcabs:
  7664. case Builtin::BIcabsl:
  7665. return Builtin::BIfabsf;
  7666. }
  7667. case AVK_Complex:
  7668. switch (AbsKind) {
  7669. default:
  7670. return 0;
  7671. case Builtin::BI__builtin_abs:
  7672. case Builtin::BI__builtin_labs:
  7673. case Builtin::BI__builtin_llabs:
  7674. case Builtin::BI__builtin_fabsf:
  7675. case Builtin::BI__builtin_fabs:
  7676. case Builtin::BI__builtin_fabsl:
  7677. return Builtin::BI__builtin_cabsf;
  7678. case Builtin::BIabs:
  7679. case Builtin::BIlabs:
  7680. case Builtin::BIllabs:
  7681. case Builtin::BIfabsf:
  7682. case Builtin::BIfabs:
  7683. case Builtin::BIfabsl:
  7684. return Builtin::BIcabsf;
  7685. }
  7686. }
  7687. llvm_unreachable("Unable to convert function");
  7688. }
  7689. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  7690. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  7691. if (!FnInfo)
  7692. return 0;
  7693. switch (FDecl->getBuiltinID()) {
  7694. default:
  7695. return 0;
  7696. case Builtin::BI__builtin_abs:
  7697. case Builtin::BI__builtin_fabs:
  7698. case Builtin::BI__builtin_fabsf:
  7699. case Builtin::BI__builtin_fabsl:
  7700. case Builtin::BI__builtin_labs:
  7701. case Builtin::BI__builtin_llabs:
  7702. case Builtin::BI__builtin_cabs:
  7703. case Builtin::BI__builtin_cabsf:
  7704. case Builtin::BI__builtin_cabsl:
  7705. case Builtin::BIabs:
  7706. case Builtin::BIlabs:
  7707. case Builtin::BIllabs:
  7708. case Builtin::BIfabs:
  7709. case Builtin::BIfabsf:
  7710. case Builtin::BIfabsl:
  7711. case Builtin::BIcabs:
  7712. case Builtin::BIcabsf:
  7713. case Builtin::BIcabsl:
  7714. return FDecl->getBuiltinID();
  7715. }
  7716. llvm_unreachable("Unknown Builtin type");
  7717. }
  7718. // If the replacement is valid, emit a note with replacement function.
  7719. // Additionally, suggest including the proper header if not already included.
  7720. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  7721. unsigned AbsKind, QualType ArgType) {
  7722. bool EmitHeaderHint = true;
  7723. const char *HeaderName = nullptr;
  7724. const char *FunctionName = nullptr;
  7725. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  7726. FunctionName = "std::abs";
  7727. if (ArgType->isIntegralOrEnumerationType()) {
  7728. HeaderName = "cstdlib";
  7729. } else if (ArgType->isRealFloatingType()) {
  7730. HeaderName = "cmath";
  7731. } else {
  7732. llvm_unreachable("Invalid Type");
  7733. }
  7734. // Lookup all std::abs
  7735. if (NamespaceDecl *Std = S.getStdNamespace()) {
  7736. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  7737. R.suppressDiagnostics();
  7738. S.LookupQualifiedName(R, Std);
  7739. for (const auto *I : R) {
  7740. const FunctionDecl *FDecl = nullptr;
  7741. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  7742. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  7743. } else {
  7744. FDecl = dyn_cast<FunctionDecl>(I);
  7745. }
  7746. if (!FDecl)
  7747. continue;
  7748. // Found std::abs(), check that they are the right ones.
  7749. if (FDecl->getNumParams() != 1)
  7750. continue;
  7751. // Check that the parameter type can handle the argument.
  7752. QualType ParamType = FDecl->getParamDecl(0)->getType();
  7753. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  7754. S.Context.getTypeSize(ArgType) <=
  7755. S.Context.getTypeSize(ParamType)) {
  7756. // Found a function, don't need the header hint.
  7757. EmitHeaderHint = false;
  7758. break;
  7759. }
  7760. }
  7761. }
  7762. } else {
  7763. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  7764. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  7765. if (HeaderName) {
  7766. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  7767. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  7768. R.suppressDiagnostics();
  7769. S.LookupName(R, S.getCurScope());
  7770. if (R.isSingleResult()) {
  7771. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  7772. if (FD && FD->getBuiltinID() == AbsKind) {
  7773. EmitHeaderHint = false;
  7774. } else {
  7775. return;
  7776. }
  7777. } else if (!R.empty()) {
  7778. return;
  7779. }
  7780. }
  7781. }
  7782. S.Diag(Loc, diag::note_replace_abs_function)
  7783. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  7784. if (!HeaderName)
  7785. return;
  7786. if (!EmitHeaderHint)
  7787. return;
  7788. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  7789. << FunctionName;
  7790. }
  7791. template <std::size_t StrLen>
  7792. static bool IsStdFunction(const FunctionDecl *FDecl,
  7793. const char (&Str)[StrLen]) {
  7794. if (!FDecl)
  7795. return false;
  7796. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  7797. return false;
  7798. if (!FDecl->isInStdNamespace())
  7799. return false;
  7800. return true;
  7801. }
  7802. // Warn when using the wrong abs() function.
  7803. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  7804. const FunctionDecl *FDecl) {
  7805. if (Call->getNumArgs() != 1)
  7806. return;
  7807. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  7808. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  7809. if (AbsKind == 0 && !IsStdAbs)
  7810. return;
  7811. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  7812. QualType ParamType = Call->getArg(0)->getType();
  7813. // Unsigned types cannot be negative. Suggest removing the absolute value
  7814. // function call.
  7815. if (ArgType->isUnsignedIntegerType()) {
  7816. const char *FunctionName =
  7817. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  7818. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  7819. Diag(Call->getExprLoc(), diag::note_remove_abs)
  7820. << FunctionName
  7821. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  7822. return;
  7823. }
  7824. // Taking the absolute value of a pointer is very suspicious, they probably
  7825. // wanted to index into an array, dereference a pointer, call a function, etc.
  7826. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  7827. unsigned DiagType = 0;
  7828. if (ArgType->isFunctionType())
  7829. DiagType = 1;
  7830. else if (ArgType->isArrayType())
  7831. DiagType = 2;
  7832. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  7833. return;
  7834. }
  7835. // std::abs has overloads which prevent most of the absolute value problems
  7836. // from occurring.
  7837. if (IsStdAbs)
  7838. return;
  7839. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  7840. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  7841. // The argument and parameter are the same kind. Check if they are the right
  7842. // size.
  7843. if (ArgValueKind == ParamValueKind) {
  7844. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  7845. return;
  7846. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  7847. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  7848. << FDecl << ArgType << ParamType;
  7849. if (NewAbsKind == 0)
  7850. return;
  7851. emitReplacement(*this, Call->getExprLoc(),
  7852. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7853. return;
  7854. }
  7855. // ArgValueKind != ParamValueKind
  7856. // The wrong type of absolute value function was used. Attempt to find the
  7857. // proper one.
  7858. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  7859. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  7860. if (NewAbsKind == 0)
  7861. return;
  7862. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  7863. << FDecl << ParamValueKind << ArgValueKind;
  7864. emitReplacement(*this, Call->getExprLoc(),
  7865. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  7866. }
  7867. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  7868. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  7869. const FunctionDecl *FDecl) {
  7870. if (!Call || !FDecl) return;
  7871. // Ignore template specializations and macros.
  7872. if (inTemplateInstantiation()) return;
  7873. if (Call->getExprLoc().isMacroID()) return;
  7874. // Only care about the one template argument, two function parameter std::max
  7875. if (Call->getNumArgs() != 2) return;
  7876. if (!IsStdFunction(FDecl, "max")) return;
  7877. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  7878. if (!ArgList) return;
  7879. if (ArgList->size() != 1) return;
  7880. // Check that template type argument is unsigned integer.
  7881. const auto& TA = ArgList->get(0);
  7882. if (TA.getKind() != TemplateArgument::Type) return;
  7883. QualType ArgType = TA.getAsType();
  7884. if (!ArgType->isUnsignedIntegerType()) return;
  7885. // See if either argument is a literal zero.
  7886. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  7887. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  7888. if (!MTE) return false;
  7889. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  7890. if (!Num) return false;
  7891. if (Num->getValue() != 0) return false;
  7892. return true;
  7893. };
  7894. const Expr *FirstArg = Call->getArg(0);
  7895. const Expr *SecondArg = Call->getArg(1);
  7896. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  7897. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  7898. // Only warn when exactly one argument is zero.
  7899. if (IsFirstArgZero == IsSecondArgZero) return;
  7900. SourceRange FirstRange = FirstArg->getSourceRange();
  7901. SourceRange SecondRange = SecondArg->getSourceRange();
  7902. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  7903. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  7904. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  7905. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  7906. SourceRange RemovalRange;
  7907. if (IsFirstArgZero) {
  7908. RemovalRange = SourceRange(FirstRange.getBegin(),
  7909. SecondRange.getBegin().getLocWithOffset(-1));
  7910. } else {
  7911. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  7912. SecondRange.getEnd());
  7913. }
  7914. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  7915. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  7916. << FixItHint::CreateRemoval(RemovalRange);
  7917. }
  7918. //===--- CHECK: Standard memory functions ---------------------------------===//
  7919. /// Takes the expression passed to the size_t parameter of functions
  7920. /// such as memcmp, strncat, etc and warns if it's a comparison.
  7921. ///
  7922. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  7923. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  7924. IdentifierInfo *FnName,
  7925. SourceLocation FnLoc,
  7926. SourceLocation RParenLoc) {
  7927. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  7928. if (!Size)
  7929. return false;
  7930. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  7931. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  7932. return false;
  7933. SourceRange SizeRange = Size->getSourceRange();
  7934. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  7935. << SizeRange << FnName;
  7936. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  7937. << FnName
  7938. << FixItHint::CreateInsertion(
  7939. S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
  7940. << FixItHint::CreateRemoval(RParenLoc);
  7941. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  7942. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  7943. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  7944. ")");
  7945. return true;
  7946. }
  7947. /// Determine whether the given type is or contains a dynamic class type
  7948. /// (e.g., whether it has a vtable).
  7949. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  7950. bool &IsContained) {
  7951. // Look through array types while ignoring qualifiers.
  7952. const Type *Ty = T->getBaseElementTypeUnsafe();
  7953. IsContained = false;
  7954. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  7955. RD = RD ? RD->getDefinition() : nullptr;
  7956. if (!RD || RD->isInvalidDecl())
  7957. return nullptr;
  7958. if (RD->isDynamicClass())
  7959. return RD;
  7960. // Check all the fields. If any bases were dynamic, the class is dynamic.
  7961. // It's impossible for a class to transitively contain itself by value, so
  7962. // infinite recursion is impossible.
  7963. for (auto *FD : RD->fields()) {
  7964. bool SubContained;
  7965. if (const CXXRecordDecl *ContainedRD =
  7966. getContainedDynamicClass(FD->getType(), SubContained)) {
  7967. IsContained = true;
  7968. return ContainedRD;
  7969. }
  7970. }
  7971. return nullptr;
  7972. }
  7973. static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
  7974. if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  7975. if (Unary->getKind() == UETT_SizeOf)
  7976. return Unary;
  7977. return nullptr;
  7978. }
  7979. /// If E is a sizeof expression, returns its argument expression,
  7980. /// otherwise returns NULL.
  7981. static const Expr *getSizeOfExprArg(const Expr *E) {
  7982. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7983. if (!SizeOf->isArgumentType())
  7984. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  7985. return nullptr;
  7986. }
  7987. /// If E is a sizeof expression, returns its argument type.
  7988. static QualType getSizeOfArgType(const Expr *E) {
  7989. if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
  7990. return SizeOf->getTypeOfArgument();
  7991. return QualType();
  7992. }
  7993. namespace {
  7994. struct SearchNonTrivialToInitializeField
  7995. : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
  7996. using Super =
  7997. DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
  7998. SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
  7999. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
  8000. SourceLocation SL) {
  8001. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8002. asDerived().visitArray(PDIK, AT, SL);
  8003. return;
  8004. }
  8005. Super::visitWithKind(PDIK, FT, SL);
  8006. }
  8007. void visitARCStrong(QualType FT, SourceLocation SL) {
  8008. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8009. }
  8010. void visitARCWeak(QualType FT, SourceLocation SL) {
  8011. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
  8012. }
  8013. void visitStruct(QualType FT, SourceLocation SL) {
  8014. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8015. visit(FD->getType(), FD->getLocation());
  8016. }
  8017. void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
  8018. const ArrayType *AT, SourceLocation SL) {
  8019. visit(getContext().getBaseElementType(AT), SL);
  8020. }
  8021. void visitTrivial(QualType FT, SourceLocation SL) {}
  8022. static void diag(QualType RT, const Expr *E, Sema &S) {
  8023. SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
  8024. }
  8025. ASTContext &getContext() { return S.getASTContext(); }
  8026. const Expr *E;
  8027. Sema &S;
  8028. };
  8029. struct SearchNonTrivialToCopyField
  8030. : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
  8031. using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
  8032. SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
  8033. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
  8034. SourceLocation SL) {
  8035. if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
  8036. asDerived().visitArray(PCK, AT, SL);
  8037. return;
  8038. }
  8039. Super::visitWithKind(PCK, FT, SL);
  8040. }
  8041. void visitARCStrong(QualType FT, SourceLocation SL) {
  8042. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8043. }
  8044. void visitARCWeak(QualType FT, SourceLocation SL) {
  8045. S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
  8046. }
  8047. void visitStruct(QualType FT, SourceLocation SL) {
  8048. for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
  8049. visit(FD->getType(), FD->getLocation());
  8050. }
  8051. void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
  8052. SourceLocation SL) {
  8053. visit(getContext().getBaseElementType(AT), SL);
  8054. }
  8055. void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
  8056. SourceLocation SL) {}
  8057. void visitTrivial(QualType FT, SourceLocation SL) {}
  8058. void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
  8059. static void diag(QualType RT, const Expr *E, Sema &S) {
  8060. SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
  8061. }
  8062. ASTContext &getContext() { return S.getASTContext(); }
  8063. const Expr *E;
  8064. Sema &S;
  8065. };
  8066. }
  8067. /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
  8068. static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
  8069. SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
  8070. if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
  8071. if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
  8072. return false;
  8073. return doesExprLikelyComputeSize(BO->getLHS()) ||
  8074. doesExprLikelyComputeSize(BO->getRHS());
  8075. }
  8076. return getAsSizeOfExpr(SizeofExpr) != nullptr;
  8077. }
  8078. /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
  8079. ///
  8080. /// \code
  8081. /// #define MACRO 0
  8082. /// foo(MACRO);
  8083. /// foo(0);
  8084. /// \endcode
  8085. ///
  8086. /// This should return true for the first call to foo, but not for the second
  8087. /// (regardless of whether foo is a macro or function).
  8088. static bool isArgumentExpandedFromMacro(SourceManager &SM,
  8089. SourceLocation CallLoc,
  8090. SourceLocation ArgLoc) {
  8091. if (!CallLoc.isMacroID())
  8092. return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
  8093. return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
  8094. SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
  8095. }
  8096. /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
  8097. /// last two arguments transposed.
  8098. static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
  8099. if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
  8100. return;
  8101. const Expr *SizeArg =
  8102. Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
  8103. auto isLiteralZero = [](const Expr *E) {
  8104. return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
  8105. };
  8106. // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
  8107. SourceLocation CallLoc = Call->getRParenLoc();
  8108. SourceManager &SM = S.getSourceManager();
  8109. if (isLiteralZero(SizeArg) &&
  8110. !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
  8111. SourceLocation DiagLoc = SizeArg->getExprLoc();
  8112. // Some platforms #define bzero to __builtin_memset. See if this is the
  8113. // case, and if so, emit a better diagnostic.
  8114. if (BId == Builtin::BIbzero ||
  8115. (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
  8116. CallLoc, SM, S.getLangOpts()) == "bzero")) {
  8117. S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
  8118. S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
  8119. } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
  8120. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
  8121. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
  8122. }
  8123. return;
  8124. }
  8125. // If the second argument to a memset is a sizeof expression and the third
  8126. // isn't, this is also likely an error. This should catch
  8127. // 'memset(buf, sizeof(buf), 0xff)'.
  8128. if (BId == Builtin::BImemset &&
  8129. doesExprLikelyComputeSize(Call->getArg(1)) &&
  8130. !doesExprLikelyComputeSize(Call->getArg(2))) {
  8131. SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
  8132. S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
  8133. S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
  8134. return;
  8135. }
  8136. }
  8137. /// Check for dangerous or invalid arguments to memset().
  8138. ///
  8139. /// This issues warnings on known problematic, dangerous or unspecified
  8140. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  8141. /// function calls.
  8142. ///
  8143. /// \param Call The call expression to diagnose.
  8144. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  8145. unsigned BId,
  8146. IdentifierInfo *FnName) {
  8147. assert(BId != 0);
  8148. // It is possible to have a non-standard definition of memset. Validate
  8149. // we have enough arguments, and if not, abort further checking.
  8150. unsigned ExpectedNumArgs =
  8151. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  8152. if (Call->getNumArgs() < ExpectedNumArgs)
  8153. return;
  8154. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  8155. BId == Builtin::BIstrndup ? 1 : 2);
  8156. unsigned LenArg =
  8157. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  8158. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  8159. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  8160. Call->getBeginLoc(), Call->getRParenLoc()))
  8161. return;
  8162. // Catch cases like 'memset(buf, sizeof(buf), 0)'.
  8163. CheckMemaccessSize(*this, BId, Call);
  8164. // We have special checking when the length is a sizeof expression.
  8165. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  8166. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  8167. llvm::FoldingSetNodeID SizeOfArgID;
  8168. // Although widely used, 'bzero' is not a standard function. Be more strict
  8169. // with the argument types before allowing diagnostics and only allow the
  8170. // form bzero(ptr, sizeof(...)).
  8171. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  8172. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  8173. return;
  8174. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  8175. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  8176. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  8177. QualType DestTy = Dest->getType();
  8178. QualType PointeeTy;
  8179. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  8180. PointeeTy = DestPtrTy->getPointeeType();
  8181. // Never warn about void type pointers. This can be used to suppress
  8182. // false positives.
  8183. if (PointeeTy->isVoidType())
  8184. continue;
  8185. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  8186. // actually comparing the expressions for equality. Because computing the
  8187. // expression IDs can be expensive, we only do this if the diagnostic is
  8188. // enabled.
  8189. if (SizeOfArg &&
  8190. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  8191. SizeOfArg->getExprLoc())) {
  8192. // We only compute IDs for expressions if the warning is enabled, and
  8193. // cache the sizeof arg's ID.
  8194. if (SizeOfArgID == llvm::FoldingSetNodeID())
  8195. SizeOfArg->Profile(SizeOfArgID, Context, true);
  8196. llvm::FoldingSetNodeID DestID;
  8197. Dest->Profile(DestID, Context, true);
  8198. if (DestID == SizeOfArgID) {
  8199. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  8200. // over sizeof(src) as well.
  8201. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  8202. StringRef ReadableName = FnName->getName();
  8203. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  8204. if (UnaryOp->getOpcode() == UO_AddrOf)
  8205. ActionIdx = 1; // If its an address-of operator, just remove it.
  8206. if (!PointeeTy->isIncompleteType() &&
  8207. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  8208. ActionIdx = 2; // If the pointee's size is sizeof(char),
  8209. // suggest an explicit length.
  8210. // If the function is defined as a builtin macro, do not show macro
  8211. // expansion.
  8212. SourceLocation SL = SizeOfArg->getExprLoc();
  8213. SourceRange DSR = Dest->getSourceRange();
  8214. SourceRange SSR = SizeOfArg->getSourceRange();
  8215. SourceManager &SM = getSourceManager();
  8216. if (SM.isMacroArgExpansion(SL)) {
  8217. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  8218. SL = SM.getSpellingLoc(SL);
  8219. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  8220. SM.getSpellingLoc(DSR.getEnd()));
  8221. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  8222. SM.getSpellingLoc(SSR.getEnd()));
  8223. }
  8224. DiagRuntimeBehavior(SL, SizeOfArg,
  8225. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  8226. << ReadableName
  8227. << PointeeTy
  8228. << DestTy
  8229. << DSR
  8230. << SSR);
  8231. DiagRuntimeBehavior(SL, SizeOfArg,
  8232. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  8233. << ActionIdx
  8234. << SSR);
  8235. break;
  8236. }
  8237. }
  8238. // Also check for cases where the sizeof argument is the exact same
  8239. // type as the memory argument, and where it points to a user-defined
  8240. // record type.
  8241. if (SizeOfArgTy != QualType()) {
  8242. if (PointeeTy->isRecordType() &&
  8243. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  8244. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  8245. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  8246. << FnName << SizeOfArgTy << ArgIdx
  8247. << PointeeTy << Dest->getSourceRange()
  8248. << LenExpr->getSourceRange());
  8249. break;
  8250. }
  8251. }
  8252. } else if (DestTy->isArrayType()) {
  8253. PointeeTy = DestTy;
  8254. }
  8255. if (PointeeTy == QualType())
  8256. continue;
  8257. // Always complain about dynamic classes.
  8258. bool IsContained;
  8259. if (const CXXRecordDecl *ContainedRD =
  8260. getContainedDynamicClass(PointeeTy, IsContained)) {
  8261. unsigned OperationType = 0;
  8262. // "overwritten" if we're warning about the destination for any call
  8263. // but memcmp; otherwise a verb appropriate to the call.
  8264. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  8265. if (BId == Builtin::BImemcpy)
  8266. OperationType = 1;
  8267. else if(BId == Builtin::BImemmove)
  8268. OperationType = 2;
  8269. else if (BId == Builtin::BImemcmp)
  8270. OperationType = 3;
  8271. }
  8272. DiagRuntimeBehavior(
  8273. Dest->getExprLoc(), Dest,
  8274. PDiag(diag::warn_dyn_class_memaccess)
  8275. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  8276. << FnName << IsContained << ContainedRD << OperationType
  8277. << Call->getCallee()->getSourceRange());
  8278. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  8279. BId != Builtin::BImemset)
  8280. DiagRuntimeBehavior(
  8281. Dest->getExprLoc(), Dest,
  8282. PDiag(diag::warn_arc_object_memaccess)
  8283. << ArgIdx << FnName << PointeeTy
  8284. << Call->getCallee()->getSourceRange());
  8285. else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
  8286. if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
  8287. RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
  8288. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8289. PDiag(diag::warn_cstruct_memaccess)
  8290. << ArgIdx << FnName << PointeeTy << 0);
  8291. SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
  8292. } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
  8293. RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
  8294. DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
  8295. PDiag(diag::warn_cstruct_memaccess)
  8296. << ArgIdx << FnName << PointeeTy << 1);
  8297. SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
  8298. } else {
  8299. continue;
  8300. }
  8301. } else
  8302. continue;
  8303. DiagRuntimeBehavior(
  8304. Dest->getExprLoc(), Dest,
  8305. PDiag(diag::note_bad_memaccess_silence)
  8306. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  8307. break;
  8308. }
  8309. }
  8310. // A little helper routine: ignore addition and subtraction of integer literals.
  8311. // This intentionally does not ignore all integer constant expressions because
  8312. // we don't want to remove sizeof().
  8313. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  8314. Ex = Ex->IgnoreParenCasts();
  8315. while (true) {
  8316. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  8317. if (!BO || !BO->isAdditiveOp())
  8318. break;
  8319. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  8320. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  8321. if (isa<IntegerLiteral>(RHS))
  8322. Ex = LHS;
  8323. else if (isa<IntegerLiteral>(LHS))
  8324. Ex = RHS;
  8325. else
  8326. break;
  8327. }
  8328. return Ex;
  8329. }
  8330. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  8331. ASTContext &Context) {
  8332. // Only handle constant-sized or VLAs, but not flexible members.
  8333. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  8334. // Only issue the FIXIT for arrays of size > 1.
  8335. if (CAT->getSize().getSExtValue() <= 1)
  8336. return false;
  8337. } else if (!Ty->isVariableArrayType()) {
  8338. return false;
  8339. }
  8340. return true;
  8341. }
  8342. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  8343. // be the size of the source, instead of the destination.
  8344. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  8345. IdentifierInfo *FnName) {
  8346. // Don't crash if the user has the wrong number of arguments
  8347. unsigned NumArgs = Call->getNumArgs();
  8348. if ((NumArgs != 3) && (NumArgs != 4))
  8349. return;
  8350. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  8351. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  8352. const Expr *CompareWithSrc = nullptr;
  8353. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  8354. Call->getBeginLoc(), Call->getRParenLoc()))
  8355. return;
  8356. // Look for 'strlcpy(dst, x, sizeof(x))'
  8357. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  8358. CompareWithSrc = Ex;
  8359. else {
  8360. // Look for 'strlcpy(dst, x, strlen(x))'
  8361. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  8362. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  8363. SizeCall->getNumArgs() == 1)
  8364. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  8365. }
  8366. }
  8367. if (!CompareWithSrc)
  8368. return;
  8369. // Determine if the argument to sizeof/strlen is equal to the source
  8370. // argument. In principle there's all kinds of things you could do
  8371. // here, for instance creating an == expression and evaluating it with
  8372. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  8373. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  8374. if (!SrcArgDRE)
  8375. return;
  8376. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  8377. if (!CompareWithSrcDRE ||
  8378. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  8379. return;
  8380. const Expr *OriginalSizeArg = Call->getArg(2);
  8381. Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
  8382. << OriginalSizeArg->getSourceRange() << FnName;
  8383. // Output a FIXIT hint if the destination is an array (rather than a
  8384. // pointer to an array). This could be enhanced to handle some
  8385. // pointers if we know the actual size, like if DstArg is 'array+2'
  8386. // we could say 'sizeof(array)-2'.
  8387. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  8388. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  8389. return;
  8390. SmallString<128> sizeString;
  8391. llvm::raw_svector_ostream OS(sizeString);
  8392. OS << "sizeof(";
  8393. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8394. OS << ")";
  8395. Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
  8396. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  8397. OS.str());
  8398. }
  8399. /// Check if two expressions refer to the same declaration.
  8400. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  8401. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  8402. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  8403. return D1->getDecl() == D2->getDecl();
  8404. return false;
  8405. }
  8406. static const Expr *getStrlenExprArg(const Expr *E) {
  8407. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8408. const FunctionDecl *FD = CE->getDirectCallee();
  8409. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  8410. return nullptr;
  8411. return CE->getArg(0)->IgnoreParenCasts();
  8412. }
  8413. return nullptr;
  8414. }
  8415. // Warn on anti-patterns as the 'size' argument to strncat.
  8416. // The correct size argument should look like following:
  8417. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  8418. void Sema::CheckStrncatArguments(const CallExpr *CE,
  8419. IdentifierInfo *FnName) {
  8420. // Don't crash if the user has the wrong number of arguments.
  8421. if (CE->getNumArgs() < 3)
  8422. return;
  8423. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  8424. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  8425. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  8426. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
  8427. CE->getRParenLoc()))
  8428. return;
  8429. // Identify common expressions, which are wrongly used as the size argument
  8430. // to strncat and may lead to buffer overflows.
  8431. unsigned PatternType = 0;
  8432. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  8433. // - sizeof(dst)
  8434. if (referToTheSameDecl(SizeOfArg, DstArg))
  8435. PatternType = 1;
  8436. // - sizeof(src)
  8437. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  8438. PatternType = 2;
  8439. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  8440. if (BE->getOpcode() == BO_Sub) {
  8441. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  8442. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  8443. // - sizeof(dst) - strlen(dst)
  8444. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  8445. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  8446. PatternType = 1;
  8447. // - sizeof(src) - (anything)
  8448. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  8449. PatternType = 2;
  8450. }
  8451. }
  8452. if (PatternType == 0)
  8453. return;
  8454. // Generate the diagnostic.
  8455. SourceLocation SL = LenArg->getBeginLoc();
  8456. SourceRange SR = LenArg->getSourceRange();
  8457. SourceManager &SM = getSourceManager();
  8458. // If the function is defined as a builtin macro, do not show macro expansion.
  8459. if (SM.isMacroArgExpansion(SL)) {
  8460. SL = SM.getSpellingLoc(SL);
  8461. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  8462. SM.getSpellingLoc(SR.getEnd()));
  8463. }
  8464. // Check if the destination is an array (rather than a pointer to an array).
  8465. QualType DstTy = DstArg->getType();
  8466. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  8467. Context);
  8468. if (!isKnownSizeArray) {
  8469. if (PatternType == 1)
  8470. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  8471. else
  8472. Diag(SL, diag::warn_strncat_src_size) << SR;
  8473. return;
  8474. }
  8475. if (PatternType == 1)
  8476. Diag(SL, diag::warn_strncat_large_size) << SR;
  8477. else
  8478. Diag(SL, diag::warn_strncat_src_size) << SR;
  8479. SmallString<128> sizeString;
  8480. llvm::raw_svector_ostream OS(sizeString);
  8481. OS << "sizeof(";
  8482. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8483. OS << ") - ";
  8484. OS << "strlen(";
  8485. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  8486. OS << ") - 1";
  8487. Diag(SL, diag::note_strncat_wrong_size)
  8488. << FixItHint::CreateReplacement(SR, OS.str());
  8489. }
  8490. void
  8491. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  8492. SourceLocation ReturnLoc,
  8493. bool isObjCMethod,
  8494. const AttrVec *Attrs,
  8495. const FunctionDecl *FD) {
  8496. // Check if the return value is null but should not be.
  8497. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  8498. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  8499. CheckNonNullExpr(*this, RetValExp))
  8500. Diag(ReturnLoc, diag::warn_null_ret)
  8501. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  8502. // C++11 [basic.stc.dynamic.allocation]p4:
  8503. // If an allocation function declared with a non-throwing
  8504. // exception-specification fails to allocate storage, it shall return
  8505. // a null pointer. Any other allocation function that fails to allocate
  8506. // storage shall indicate failure only by throwing an exception [...]
  8507. if (FD) {
  8508. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  8509. if (Op == OO_New || Op == OO_Array_New) {
  8510. const FunctionProtoType *Proto
  8511. = FD->getType()->castAs<FunctionProtoType>();
  8512. if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
  8513. CheckNonNullExpr(*this, RetValExp))
  8514. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  8515. << FD << getLangOpts().CPlusPlus11;
  8516. }
  8517. }
  8518. }
  8519. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  8520. /// Check for comparisons of floating point operands using != and ==.
  8521. /// Issue a warning if these are no self-comparisons, as they are not likely
  8522. /// to do what the programmer intended.
  8523. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  8524. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  8525. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  8526. // Special case: check for x == x (which is OK).
  8527. // Do not emit warnings for such cases.
  8528. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  8529. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  8530. if (DRL->getDecl() == DRR->getDecl())
  8531. return;
  8532. // Special case: check for comparisons against literals that can be exactly
  8533. // represented by APFloat. In such cases, do not emit a warning. This
  8534. // is a heuristic: often comparison against such literals are used to
  8535. // detect if a value in a variable has not changed. This clearly can
  8536. // lead to false negatives.
  8537. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  8538. if (FLL->isExact())
  8539. return;
  8540. } else
  8541. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  8542. if (FLR->isExact())
  8543. return;
  8544. // Check for comparisons with builtin types.
  8545. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  8546. if (CL->getBuiltinCallee())
  8547. return;
  8548. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  8549. if (CR->getBuiltinCallee())
  8550. return;
  8551. // Emit the diagnostic.
  8552. Diag(Loc, diag::warn_floatingpoint_eq)
  8553. << LHS->getSourceRange() << RHS->getSourceRange();
  8554. }
  8555. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  8556. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  8557. namespace {
  8558. /// Structure recording the 'active' range of an integer-valued
  8559. /// expression.
  8560. struct IntRange {
  8561. /// The number of bits active in the int.
  8562. unsigned Width;
  8563. /// True if the int is known not to have negative values.
  8564. bool NonNegative;
  8565. IntRange(unsigned Width, bool NonNegative)
  8566. : Width(Width), NonNegative(NonNegative) {}
  8567. /// Returns the range of the bool type.
  8568. static IntRange forBoolType() {
  8569. return IntRange(1, true);
  8570. }
  8571. /// Returns the range of an opaque value of the given integral type.
  8572. static IntRange forValueOfType(ASTContext &C, QualType T) {
  8573. return forValueOfCanonicalType(C,
  8574. T->getCanonicalTypeInternal().getTypePtr());
  8575. }
  8576. /// Returns the range of an opaque value of a canonical integral type.
  8577. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  8578. assert(T->isCanonicalUnqualified());
  8579. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8580. T = VT->getElementType().getTypePtr();
  8581. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8582. T = CT->getElementType().getTypePtr();
  8583. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8584. T = AT->getValueType().getTypePtr();
  8585. if (!C.getLangOpts().CPlusPlus) {
  8586. // For enum types in C code, use the underlying datatype.
  8587. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8588. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  8589. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  8590. // For enum types in C++, use the known bit width of the enumerators.
  8591. EnumDecl *Enum = ET->getDecl();
  8592. // In C++11, enums can have a fixed underlying type. Use this type to
  8593. // compute the range.
  8594. if (Enum->isFixed()) {
  8595. return IntRange(C.getIntWidth(QualType(T, 0)),
  8596. !ET->isSignedIntegerOrEnumerationType());
  8597. }
  8598. unsigned NumPositive = Enum->getNumPositiveBits();
  8599. unsigned NumNegative = Enum->getNumNegativeBits();
  8600. if (NumNegative == 0)
  8601. return IntRange(NumPositive, true/*NonNegative*/);
  8602. else
  8603. return IntRange(std::max(NumPositive + 1, NumNegative),
  8604. false/*NonNegative*/);
  8605. }
  8606. const BuiltinType *BT = cast<BuiltinType>(T);
  8607. assert(BT->isInteger());
  8608. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8609. }
  8610. /// Returns the "target" range of a canonical integral type, i.e.
  8611. /// the range of values expressible in the type.
  8612. ///
  8613. /// This matches forValueOfCanonicalType except that enums have the
  8614. /// full range of their type, not the range of their enumerators.
  8615. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  8616. assert(T->isCanonicalUnqualified());
  8617. if (const VectorType *VT = dyn_cast<VectorType>(T))
  8618. T = VT->getElementType().getTypePtr();
  8619. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  8620. T = CT->getElementType().getTypePtr();
  8621. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  8622. T = AT->getValueType().getTypePtr();
  8623. if (const EnumType *ET = dyn_cast<EnumType>(T))
  8624. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  8625. const BuiltinType *BT = cast<BuiltinType>(T);
  8626. assert(BT->isInteger());
  8627. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  8628. }
  8629. /// Returns the supremum of two ranges: i.e. their conservative merge.
  8630. static IntRange join(IntRange L, IntRange R) {
  8631. return IntRange(std::max(L.Width, R.Width),
  8632. L.NonNegative && R.NonNegative);
  8633. }
  8634. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  8635. static IntRange meet(IntRange L, IntRange R) {
  8636. return IntRange(std::min(L.Width, R.Width),
  8637. L.NonNegative || R.NonNegative);
  8638. }
  8639. };
  8640. } // namespace
  8641. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  8642. unsigned MaxWidth) {
  8643. if (value.isSigned() && value.isNegative())
  8644. return IntRange(value.getMinSignedBits(), false);
  8645. if (value.getBitWidth() > MaxWidth)
  8646. value = value.trunc(MaxWidth);
  8647. // isNonNegative() just checks the sign bit without considering
  8648. // signedness.
  8649. return IntRange(value.getActiveBits(), true);
  8650. }
  8651. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  8652. unsigned MaxWidth) {
  8653. if (result.isInt())
  8654. return GetValueRange(C, result.getInt(), MaxWidth);
  8655. if (result.isVector()) {
  8656. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  8657. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  8658. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  8659. R = IntRange::join(R, El);
  8660. }
  8661. return R;
  8662. }
  8663. if (result.isComplexInt()) {
  8664. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  8665. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  8666. return IntRange::join(R, I);
  8667. }
  8668. // This can happen with lossless casts to intptr_t of "based" lvalues.
  8669. // Assume it might use arbitrary bits.
  8670. // FIXME: The only reason we need to pass the type in here is to get
  8671. // the sign right on this one case. It would be nice if APValue
  8672. // preserved this.
  8673. assert(result.isLValue() || result.isAddrLabelDiff());
  8674. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  8675. }
  8676. static QualType GetExprType(const Expr *E) {
  8677. QualType Ty = E->getType();
  8678. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  8679. Ty = AtomicRHS->getValueType();
  8680. return Ty;
  8681. }
  8682. /// Pseudo-evaluate the given integer expression, estimating the
  8683. /// range of values it might take.
  8684. ///
  8685. /// \param MaxWidth - the width to which the value will be truncated
  8686. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  8687. E = E->IgnoreParens();
  8688. // Try a full evaluation first.
  8689. Expr::EvalResult result;
  8690. if (E->EvaluateAsRValue(result, C))
  8691. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  8692. // I think we only want to look through implicit casts here; if the
  8693. // user has an explicit widening cast, we should treat the value as
  8694. // being of the new, wider type.
  8695. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  8696. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  8697. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  8698. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  8699. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  8700. CE->getCastKind() == CK_BooleanToSignedIntegral;
  8701. // Assume that non-integer casts can span the full range of the type.
  8702. if (!isIntegerCast)
  8703. return OutputTypeRange;
  8704. IntRange SubRange
  8705. = GetExprRange(C, CE->getSubExpr(),
  8706. std::min(MaxWidth, OutputTypeRange.Width));
  8707. // Bail out if the subexpr's range is as wide as the cast type.
  8708. if (SubRange.Width >= OutputTypeRange.Width)
  8709. return OutputTypeRange;
  8710. // Otherwise, we take the smaller width, and we're non-negative if
  8711. // either the output type or the subexpr is.
  8712. return IntRange(SubRange.Width,
  8713. SubRange.NonNegative || OutputTypeRange.NonNegative);
  8714. }
  8715. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  8716. // If we can fold the condition, just take that operand.
  8717. bool CondResult;
  8718. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  8719. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  8720. : CO->getFalseExpr(),
  8721. MaxWidth);
  8722. // Otherwise, conservatively merge.
  8723. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  8724. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  8725. return IntRange::join(L, R);
  8726. }
  8727. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  8728. switch (BO->getOpcode()) {
  8729. case BO_Cmp:
  8730. llvm_unreachable("builtin <=> should have class type");
  8731. // Boolean-valued operations are single-bit and positive.
  8732. case BO_LAnd:
  8733. case BO_LOr:
  8734. case BO_LT:
  8735. case BO_GT:
  8736. case BO_LE:
  8737. case BO_GE:
  8738. case BO_EQ:
  8739. case BO_NE:
  8740. return IntRange::forBoolType();
  8741. // The type of the assignments is the type of the LHS, so the RHS
  8742. // is not necessarily the same type.
  8743. case BO_MulAssign:
  8744. case BO_DivAssign:
  8745. case BO_RemAssign:
  8746. case BO_AddAssign:
  8747. case BO_SubAssign:
  8748. case BO_XorAssign:
  8749. case BO_OrAssign:
  8750. // TODO: bitfields?
  8751. return IntRange::forValueOfType(C, GetExprType(E));
  8752. // Simple assignments just pass through the RHS, which will have
  8753. // been coerced to the LHS type.
  8754. case BO_Assign:
  8755. // TODO: bitfields?
  8756. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8757. // Operations with opaque sources are black-listed.
  8758. case BO_PtrMemD:
  8759. case BO_PtrMemI:
  8760. return IntRange::forValueOfType(C, GetExprType(E));
  8761. // Bitwise-and uses the *infinum* of the two source ranges.
  8762. case BO_And:
  8763. case BO_AndAssign:
  8764. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  8765. GetExprRange(C, BO->getRHS(), MaxWidth));
  8766. // Left shift gets black-listed based on a judgement call.
  8767. case BO_Shl:
  8768. // ...except that we want to treat '1 << (blah)' as logically
  8769. // positive. It's an important idiom.
  8770. if (IntegerLiteral *I
  8771. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  8772. if (I->getValue() == 1) {
  8773. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  8774. return IntRange(R.Width, /*NonNegative*/ true);
  8775. }
  8776. }
  8777. LLVM_FALLTHROUGH;
  8778. case BO_ShlAssign:
  8779. return IntRange::forValueOfType(C, GetExprType(E));
  8780. // Right shift by a constant can narrow its left argument.
  8781. case BO_Shr:
  8782. case BO_ShrAssign: {
  8783. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8784. // If the shift amount is a positive constant, drop the width by
  8785. // that much.
  8786. llvm::APSInt shift;
  8787. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  8788. shift.isNonNegative()) {
  8789. unsigned zext = shift.getZExtValue();
  8790. if (zext >= L.Width)
  8791. L.Width = (L.NonNegative ? 0 : 1);
  8792. else
  8793. L.Width -= zext;
  8794. }
  8795. return L;
  8796. }
  8797. // Comma acts as its right operand.
  8798. case BO_Comma:
  8799. return GetExprRange(C, BO->getRHS(), MaxWidth);
  8800. // Black-list pointer subtractions.
  8801. case BO_Sub:
  8802. if (BO->getLHS()->getType()->isPointerType())
  8803. return IntRange::forValueOfType(C, GetExprType(E));
  8804. break;
  8805. // The width of a division result is mostly determined by the size
  8806. // of the LHS.
  8807. case BO_Div: {
  8808. // Don't 'pre-truncate' the operands.
  8809. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8810. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8811. // If the divisor is constant, use that.
  8812. llvm::APSInt divisor;
  8813. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  8814. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  8815. if (log2 >= L.Width)
  8816. L.Width = (L.NonNegative ? 0 : 1);
  8817. else
  8818. L.Width = std::min(L.Width - log2, MaxWidth);
  8819. return L;
  8820. }
  8821. // Otherwise, just use the LHS's width.
  8822. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8823. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  8824. }
  8825. // The result of a remainder can't be larger than the result of
  8826. // either side.
  8827. case BO_Rem: {
  8828. // Don't 'pre-truncate' the operands.
  8829. unsigned opWidth = C.getIntWidth(GetExprType(E));
  8830. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  8831. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  8832. IntRange meet = IntRange::meet(L, R);
  8833. meet.Width = std::min(meet.Width, MaxWidth);
  8834. return meet;
  8835. }
  8836. // The default behavior is okay for these.
  8837. case BO_Mul:
  8838. case BO_Add:
  8839. case BO_Xor:
  8840. case BO_Or:
  8841. break;
  8842. }
  8843. // The default case is to treat the operation as if it were closed
  8844. // on the narrowest type that encompasses both operands.
  8845. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  8846. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  8847. return IntRange::join(L, R);
  8848. }
  8849. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  8850. switch (UO->getOpcode()) {
  8851. // Boolean-valued operations are white-listed.
  8852. case UO_LNot:
  8853. return IntRange::forBoolType();
  8854. // Operations with opaque sources are black-listed.
  8855. case UO_Deref:
  8856. case UO_AddrOf: // should be impossible
  8857. return IntRange::forValueOfType(C, GetExprType(E));
  8858. default:
  8859. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  8860. }
  8861. }
  8862. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  8863. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  8864. if (const auto *BitField = E->getSourceBitField())
  8865. return IntRange(BitField->getBitWidthValue(C),
  8866. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  8867. return IntRange::forValueOfType(C, GetExprType(E));
  8868. }
  8869. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  8870. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  8871. }
  8872. /// Checks whether the given value, which currently has the given
  8873. /// source semantics, has the same value when coerced through the
  8874. /// target semantics.
  8875. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  8876. const llvm::fltSemantics &Src,
  8877. const llvm::fltSemantics &Tgt) {
  8878. llvm::APFloat truncated = value;
  8879. bool ignored;
  8880. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8881. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  8882. return truncated.bitwiseIsEqual(value);
  8883. }
  8884. /// Checks whether the given value, which currently has the given
  8885. /// source semantics, has the same value when coerced through the
  8886. /// target semantics.
  8887. ///
  8888. /// The value might be a vector of floats (or a complex number).
  8889. static bool IsSameFloatAfterCast(const APValue &value,
  8890. const llvm::fltSemantics &Src,
  8891. const llvm::fltSemantics &Tgt) {
  8892. if (value.isFloat())
  8893. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  8894. if (value.isVector()) {
  8895. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  8896. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  8897. return false;
  8898. return true;
  8899. }
  8900. assert(value.isComplexFloat());
  8901. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  8902. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  8903. }
  8904. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  8905. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  8906. // Suppress cases where we are comparing against an enum constant.
  8907. if (const DeclRefExpr *DR =
  8908. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  8909. if (isa<EnumConstantDecl>(DR->getDecl()))
  8910. return true;
  8911. // Suppress cases where the '0' value is expanded from a macro.
  8912. if (E->getBeginLoc().isMacroID())
  8913. return true;
  8914. return false;
  8915. }
  8916. static bool isKnownToHaveUnsignedValue(Expr *E) {
  8917. return E->getType()->isIntegerType() &&
  8918. (!E->getType()->isSignedIntegerType() ||
  8919. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  8920. }
  8921. namespace {
  8922. /// The promoted range of values of a type. In general this has the
  8923. /// following structure:
  8924. ///
  8925. /// |-----------| . . . |-----------|
  8926. /// ^ ^ ^ ^
  8927. /// Min HoleMin HoleMax Max
  8928. ///
  8929. /// ... where there is only a hole if a signed type is promoted to unsigned
  8930. /// (in which case Min and Max are the smallest and largest representable
  8931. /// values).
  8932. struct PromotedRange {
  8933. // Min, or HoleMax if there is a hole.
  8934. llvm::APSInt PromotedMin;
  8935. // Max, or HoleMin if there is a hole.
  8936. llvm::APSInt PromotedMax;
  8937. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  8938. if (R.Width == 0)
  8939. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  8940. else if (R.Width >= BitWidth && !Unsigned) {
  8941. // Promotion made the type *narrower*. This happens when promoting
  8942. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  8943. // Treat all values of 'signed int' as being in range for now.
  8944. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  8945. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  8946. } else {
  8947. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  8948. .extOrTrunc(BitWidth);
  8949. PromotedMin.setIsUnsigned(Unsigned);
  8950. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  8951. .extOrTrunc(BitWidth);
  8952. PromotedMax.setIsUnsigned(Unsigned);
  8953. }
  8954. }
  8955. // Determine whether this range is contiguous (has no hole).
  8956. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  8957. // Where a constant value is within the range.
  8958. enum ComparisonResult {
  8959. LT = 0x1,
  8960. LE = 0x2,
  8961. GT = 0x4,
  8962. GE = 0x8,
  8963. EQ = 0x10,
  8964. NE = 0x20,
  8965. InRangeFlag = 0x40,
  8966. Less = LE | LT | NE,
  8967. Min = LE | InRangeFlag,
  8968. InRange = InRangeFlag,
  8969. Max = GE | InRangeFlag,
  8970. Greater = GE | GT | NE,
  8971. OnlyValue = LE | GE | EQ | InRangeFlag,
  8972. InHole = NE
  8973. };
  8974. ComparisonResult compare(const llvm::APSInt &Value) const {
  8975. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  8976. Value.isUnsigned() == PromotedMin.isUnsigned());
  8977. if (!isContiguous()) {
  8978. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  8979. if (Value.isMinValue()) return Min;
  8980. if (Value.isMaxValue()) return Max;
  8981. if (Value >= PromotedMin) return InRange;
  8982. if (Value <= PromotedMax) return InRange;
  8983. return InHole;
  8984. }
  8985. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  8986. case -1: return Less;
  8987. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  8988. case 1:
  8989. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  8990. case -1: return InRange;
  8991. case 0: return Max;
  8992. case 1: return Greater;
  8993. }
  8994. }
  8995. llvm_unreachable("impossible compare result");
  8996. }
  8997. static llvm::Optional<StringRef>
  8998. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  8999. if (Op == BO_Cmp) {
  9000. ComparisonResult LTFlag = LT, GTFlag = GT;
  9001. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  9002. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  9003. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  9004. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  9005. return llvm::None;
  9006. }
  9007. ComparisonResult TrueFlag, FalseFlag;
  9008. if (Op == BO_EQ) {
  9009. TrueFlag = EQ;
  9010. FalseFlag = NE;
  9011. } else if (Op == BO_NE) {
  9012. TrueFlag = NE;
  9013. FalseFlag = EQ;
  9014. } else {
  9015. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  9016. TrueFlag = LT;
  9017. FalseFlag = GE;
  9018. } else {
  9019. TrueFlag = GT;
  9020. FalseFlag = LE;
  9021. }
  9022. if (Op == BO_GE || Op == BO_LE)
  9023. std::swap(TrueFlag, FalseFlag);
  9024. }
  9025. if (R & TrueFlag)
  9026. return StringRef("true");
  9027. if (R & FalseFlag)
  9028. return StringRef("false");
  9029. return llvm::None;
  9030. }
  9031. };
  9032. }
  9033. static bool HasEnumType(Expr *E) {
  9034. // Strip off implicit integral promotions.
  9035. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  9036. if (ICE->getCastKind() != CK_IntegralCast &&
  9037. ICE->getCastKind() != CK_NoOp)
  9038. break;
  9039. E = ICE->getSubExpr();
  9040. }
  9041. return E->getType()->isEnumeralType();
  9042. }
  9043. static int classifyConstantValue(Expr *Constant) {
  9044. // The values of this enumeration are used in the diagnostics
  9045. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  9046. enum ConstantValueKind {
  9047. Miscellaneous = 0,
  9048. LiteralTrue,
  9049. LiteralFalse
  9050. };
  9051. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  9052. return BL->getValue() ? ConstantValueKind::LiteralTrue
  9053. : ConstantValueKind::LiteralFalse;
  9054. return ConstantValueKind::Miscellaneous;
  9055. }
  9056. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  9057. Expr *Constant, Expr *Other,
  9058. const llvm::APSInt &Value,
  9059. bool RhsConstant) {
  9060. if (S.inTemplateInstantiation())
  9061. return false;
  9062. Expr *OriginalOther = Other;
  9063. Constant = Constant->IgnoreParenImpCasts();
  9064. Other = Other->IgnoreParenImpCasts();
  9065. // Suppress warnings on tautological comparisons between values of the same
  9066. // enumeration type. There are only two ways we could warn on this:
  9067. // - If the constant is outside the range of representable values of
  9068. // the enumeration. In such a case, we should warn about the cast
  9069. // to enumeration type, not about the comparison.
  9070. // - If the constant is the maximum / minimum in-range value. For an
  9071. // enumeratin type, such comparisons can be meaningful and useful.
  9072. if (Constant->getType()->isEnumeralType() &&
  9073. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  9074. return false;
  9075. // TODO: Investigate using GetExprRange() to get tighter bounds
  9076. // on the bit ranges.
  9077. QualType OtherT = Other->getType();
  9078. if (const auto *AT = OtherT->getAs<AtomicType>())
  9079. OtherT = AT->getValueType();
  9080. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  9081. // Whether we're treating Other as being a bool because of the form of
  9082. // expression despite it having another type (typically 'int' in C).
  9083. bool OtherIsBooleanDespiteType =
  9084. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  9085. if (OtherIsBooleanDespiteType)
  9086. OtherRange = IntRange::forBoolType();
  9087. // Determine the promoted range of the other type and see if a comparison of
  9088. // the constant against that range is tautological.
  9089. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  9090. Value.isUnsigned());
  9091. auto Cmp = OtherPromotedRange.compare(Value);
  9092. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  9093. if (!Result)
  9094. return false;
  9095. // Suppress the diagnostic for an in-range comparison if the constant comes
  9096. // from a macro or enumerator. We don't want to diagnose
  9097. //
  9098. // some_long_value <= INT_MAX
  9099. //
  9100. // when sizeof(int) == sizeof(long).
  9101. bool InRange = Cmp & PromotedRange::InRangeFlag;
  9102. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  9103. return false;
  9104. // If this is a comparison to an enum constant, include that
  9105. // constant in the diagnostic.
  9106. const EnumConstantDecl *ED = nullptr;
  9107. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  9108. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  9109. // Should be enough for uint128 (39 decimal digits)
  9110. SmallString<64> PrettySourceValue;
  9111. llvm::raw_svector_ostream OS(PrettySourceValue);
  9112. if (ED)
  9113. OS << '\'' << *ED << "' (" << Value << ")";
  9114. else
  9115. OS << Value;
  9116. // FIXME: We use a somewhat different formatting for the in-range cases and
  9117. // cases involving boolean values for historical reasons. We should pick a
  9118. // consistent way of presenting these diagnostics.
  9119. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  9120. S.DiagRuntimeBehavior(
  9121. E->getOperatorLoc(), E,
  9122. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  9123. : diag::warn_tautological_bool_compare)
  9124. << OS.str() << classifyConstantValue(Constant)
  9125. << OtherT << OtherIsBooleanDespiteType << *Result
  9126. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  9127. } else {
  9128. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  9129. ? (HasEnumType(OriginalOther)
  9130. ? diag::warn_unsigned_enum_always_true_comparison
  9131. : diag::warn_unsigned_always_true_comparison)
  9132. : diag::warn_tautological_constant_compare;
  9133. S.Diag(E->getOperatorLoc(), Diag)
  9134. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  9135. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  9136. }
  9137. return true;
  9138. }
  9139. /// Analyze the operands of the given comparison. Implements the
  9140. /// fallback case from AnalyzeComparison.
  9141. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  9142. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9143. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9144. }
  9145. /// Implements -Wsign-compare.
  9146. ///
  9147. /// \param E the binary operator to check for warnings
  9148. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  9149. // The type the comparison is being performed in.
  9150. QualType T = E->getLHS()->getType();
  9151. // Only analyze comparison operators where both sides have been converted to
  9152. // the same type.
  9153. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  9154. return AnalyzeImpConvsInComparison(S, E);
  9155. // Don't analyze value-dependent comparisons directly.
  9156. if (E->isValueDependent())
  9157. return AnalyzeImpConvsInComparison(S, E);
  9158. Expr *LHS = E->getLHS();
  9159. Expr *RHS = E->getRHS();
  9160. if (T->isIntegralType(S.Context)) {
  9161. llvm::APSInt RHSValue;
  9162. llvm::APSInt LHSValue;
  9163. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  9164. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  9165. // We don't care about expressions whose result is a constant.
  9166. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  9167. return AnalyzeImpConvsInComparison(S, E);
  9168. // We only care about expressions where just one side is literal
  9169. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  9170. // Is the constant on the RHS or LHS?
  9171. const bool RhsConstant = IsRHSIntegralLiteral;
  9172. Expr *Const = RhsConstant ? RHS : LHS;
  9173. Expr *Other = RhsConstant ? LHS : RHS;
  9174. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  9175. // Check whether an integer constant comparison results in a value
  9176. // of 'true' or 'false'.
  9177. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  9178. return AnalyzeImpConvsInComparison(S, E);
  9179. }
  9180. }
  9181. if (!T->hasUnsignedIntegerRepresentation()) {
  9182. // We don't do anything special if this isn't an unsigned integral
  9183. // comparison: we're only interested in integral comparisons, and
  9184. // signed comparisons only happen in cases we don't care to warn about.
  9185. return AnalyzeImpConvsInComparison(S, E);
  9186. }
  9187. LHS = LHS->IgnoreParenImpCasts();
  9188. RHS = RHS->IgnoreParenImpCasts();
  9189. if (!S.getLangOpts().CPlusPlus) {
  9190. // Avoid warning about comparison of integers with different signs when
  9191. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  9192. // the type of `E`.
  9193. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  9194. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9195. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  9196. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  9197. }
  9198. // Check to see if one of the (unmodified) operands is of different
  9199. // signedness.
  9200. Expr *signedOperand, *unsignedOperand;
  9201. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  9202. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  9203. "unsigned comparison between two signed integer expressions?");
  9204. signedOperand = LHS;
  9205. unsignedOperand = RHS;
  9206. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  9207. signedOperand = RHS;
  9208. unsignedOperand = LHS;
  9209. } else {
  9210. return AnalyzeImpConvsInComparison(S, E);
  9211. }
  9212. // Otherwise, calculate the effective range of the signed operand.
  9213. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  9214. // Go ahead and analyze implicit conversions in the operands. Note
  9215. // that we skip the implicit conversions on both sides.
  9216. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  9217. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  9218. // If the signed range is non-negative, -Wsign-compare won't fire.
  9219. if (signedRange.NonNegative)
  9220. return;
  9221. // For (in)equality comparisons, if the unsigned operand is a
  9222. // constant which cannot collide with a overflowed signed operand,
  9223. // then reinterpreting the signed operand as unsigned will not
  9224. // change the result of the comparison.
  9225. if (E->isEqualityOp()) {
  9226. unsigned comparisonWidth = S.Context.getIntWidth(T);
  9227. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  9228. // We should never be unable to prove that the unsigned operand is
  9229. // non-negative.
  9230. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  9231. if (unsignedRange.Width < comparisonWidth)
  9232. return;
  9233. }
  9234. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  9235. S.PDiag(diag::warn_mixed_sign_comparison)
  9236. << LHS->getType() << RHS->getType()
  9237. << LHS->getSourceRange() << RHS->getSourceRange());
  9238. }
  9239. /// Analyzes an attempt to assign the given value to a bitfield.
  9240. ///
  9241. /// Returns true if there was something fishy about the attempt.
  9242. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  9243. SourceLocation InitLoc) {
  9244. assert(Bitfield->isBitField());
  9245. if (Bitfield->isInvalidDecl())
  9246. return false;
  9247. // White-list bool bitfields.
  9248. QualType BitfieldType = Bitfield->getType();
  9249. if (BitfieldType->isBooleanType())
  9250. return false;
  9251. if (BitfieldType->isEnumeralType()) {
  9252. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  9253. // If the underlying enum type was not explicitly specified as an unsigned
  9254. // type and the enum contain only positive values, MSVC++ will cause an
  9255. // inconsistency by storing this as a signed type.
  9256. if (S.getLangOpts().CPlusPlus11 &&
  9257. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  9258. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  9259. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  9260. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  9261. << BitfieldEnumDecl->getNameAsString();
  9262. }
  9263. }
  9264. if (Bitfield->getType()->isBooleanType())
  9265. return false;
  9266. // Ignore value- or type-dependent expressions.
  9267. if (Bitfield->getBitWidth()->isValueDependent() ||
  9268. Bitfield->getBitWidth()->isTypeDependent() ||
  9269. Init->isValueDependent() ||
  9270. Init->isTypeDependent())
  9271. return false;
  9272. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  9273. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  9274. Expr::EvalResult Result;
  9275. if (!OriginalInit->EvaluateAsInt(Result, S.Context,
  9276. Expr::SE_AllowSideEffects)) {
  9277. // The RHS is not constant. If the RHS has an enum type, make sure the
  9278. // bitfield is wide enough to hold all the values of the enum without
  9279. // truncation.
  9280. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  9281. EnumDecl *ED = EnumTy->getDecl();
  9282. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  9283. // Enum types are implicitly signed on Windows, so check if there are any
  9284. // negative enumerators to see if the enum was intended to be signed or
  9285. // not.
  9286. bool SignedEnum = ED->getNumNegativeBits() > 0;
  9287. // Check for surprising sign changes when assigning enum values to a
  9288. // bitfield of different signedness. If the bitfield is signed and we
  9289. // have exactly the right number of bits to store this unsigned enum,
  9290. // suggest changing the enum to an unsigned type. This typically happens
  9291. // on Windows where unfixed enums always use an underlying type of 'int'.
  9292. unsigned DiagID = 0;
  9293. if (SignedEnum && !SignedBitfield) {
  9294. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  9295. } else if (SignedBitfield && !SignedEnum &&
  9296. ED->getNumPositiveBits() == FieldWidth) {
  9297. DiagID = diag::warn_signed_bitfield_enum_conversion;
  9298. }
  9299. if (DiagID) {
  9300. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  9301. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  9302. SourceRange TypeRange =
  9303. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  9304. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  9305. << SignedEnum << TypeRange;
  9306. }
  9307. // Compute the required bitwidth. If the enum has negative values, we need
  9308. // one more bit than the normal number of positive bits to represent the
  9309. // sign bit.
  9310. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  9311. ED->getNumNegativeBits())
  9312. : ED->getNumPositiveBits();
  9313. // Check the bitwidth.
  9314. if (BitsNeeded > FieldWidth) {
  9315. Expr *WidthExpr = Bitfield->getBitWidth();
  9316. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  9317. << Bitfield << ED;
  9318. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  9319. << BitsNeeded << ED << WidthExpr->getSourceRange();
  9320. }
  9321. }
  9322. return false;
  9323. }
  9324. llvm::APSInt Value = Result.Val.getInt();
  9325. unsigned OriginalWidth = Value.getBitWidth();
  9326. if (!Value.isSigned() || Value.isNegative())
  9327. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  9328. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  9329. OriginalWidth = Value.getMinSignedBits();
  9330. if (OriginalWidth <= FieldWidth)
  9331. return false;
  9332. // Compute the value which the bitfield will contain.
  9333. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  9334. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  9335. // Check whether the stored value is equal to the original value.
  9336. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  9337. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  9338. return false;
  9339. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  9340. // therefore don't strictly fit into a signed bitfield of width 1.
  9341. if (FieldWidth == 1 && Value == 1)
  9342. return false;
  9343. std::string PrettyValue = Value.toString(10);
  9344. std::string PrettyTrunc = TruncatedValue.toString(10);
  9345. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  9346. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  9347. << Init->getSourceRange();
  9348. return true;
  9349. }
  9350. /// Analyze the given simple or compound assignment for warning-worthy
  9351. /// operations.
  9352. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  9353. // Just recurse on the LHS.
  9354. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9355. // We want to recurse on the RHS as normal unless we're assigning to
  9356. // a bitfield.
  9357. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  9358. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  9359. E->getOperatorLoc())) {
  9360. // Recurse, ignoring any implicit conversions on the RHS.
  9361. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  9362. E->getOperatorLoc());
  9363. }
  9364. }
  9365. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9366. // Diagnose implicitly sequentially-consistent atomic assignment.
  9367. if (E->getLHS()->getType()->isAtomicType())
  9368. S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  9369. }
  9370. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9371. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  9372. SourceLocation CContext, unsigned diag,
  9373. bool pruneControlFlow = false) {
  9374. if (pruneControlFlow) {
  9375. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9376. S.PDiag(diag)
  9377. << SourceType << T << E->getSourceRange()
  9378. << SourceRange(CContext));
  9379. return;
  9380. }
  9381. S.Diag(E->getExprLoc(), diag)
  9382. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  9383. }
  9384. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  9385. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  9386. SourceLocation CContext,
  9387. unsigned diag, bool pruneControlFlow = false) {
  9388. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  9389. }
  9390. /// Diagnose an implicit cast from a floating point value to an integer value.
  9391. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  9392. SourceLocation CContext) {
  9393. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  9394. const bool PruneWarnings = S.inTemplateInstantiation();
  9395. Expr *InnerE = E->IgnoreParenImpCasts();
  9396. // We also want to warn on, e.g., "int i = -1.234"
  9397. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  9398. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  9399. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  9400. const bool IsLiteral =
  9401. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  9402. llvm::APFloat Value(0.0);
  9403. bool IsConstant =
  9404. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  9405. if (!IsConstant) {
  9406. return DiagnoseImpCast(S, E, T, CContext,
  9407. diag::warn_impcast_float_integer, PruneWarnings);
  9408. }
  9409. bool isExact = false;
  9410. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  9411. T->hasUnsignedIntegerRepresentation());
  9412. llvm::APFloat::opStatus Result = Value.convertToInteger(
  9413. IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
  9414. if (Result == llvm::APFloat::opOK && isExact) {
  9415. if (IsLiteral) return;
  9416. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  9417. PruneWarnings);
  9418. }
  9419. // Conversion of a floating-point value to a non-bool integer where the
  9420. // integral part cannot be represented by the integer type is undefined.
  9421. if (!IsBool && Result == llvm::APFloat::opInvalidOp)
  9422. return DiagnoseImpCast(
  9423. S, E, T, CContext,
  9424. IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
  9425. : diag::warn_impcast_float_to_integer_out_of_range,
  9426. PruneWarnings);
  9427. unsigned DiagID = 0;
  9428. if (IsLiteral) {
  9429. // Warn on floating point literal to integer.
  9430. DiagID = diag::warn_impcast_literal_float_to_integer;
  9431. } else if (IntegerValue == 0) {
  9432. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  9433. return DiagnoseImpCast(S, E, T, CContext,
  9434. diag::warn_impcast_float_integer, PruneWarnings);
  9435. }
  9436. // Warn on non-zero to zero conversion.
  9437. DiagID = diag::warn_impcast_float_to_integer_zero;
  9438. } else {
  9439. if (IntegerValue.isUnsigned()) {
  9440. if (!IntegerValue.isMaxValue()) {
  9441. return DiagnoseImpCast(S, E, T, CContext,
  9442. diag::warn_impcast_float_integer, PruneWarnings);
  9443. }
  9444. } else { // IntegerValue.isSigned()
  9445. if (!IntegerValue.isMaxSignedValue() &&
  9446. !IntegerValue.isMinSignedValue()) {
  9447. return DiagnoseImpCast(S, E, T, CContext,
  9448. diag::warn_impcast_float_integer, PruneWarnings);
  9449. }
  9450. }
  9451. // Warn on evaluatable floating point expression to integer conversion.
  9452. DiagID = diag::warn_impcast_float_to_integer;
  9453. }
  9454. // FIXME: Force the precision of the source value down so we don't print
  9455. // digits which are usually useless (we don't really care here if we
  9456. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  9457. // would automatically print the shortest representation, but it's a bit
  9458. // tricky to implement.
  9459. SmallString<16> PrettySourceValue;
  9460. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  9461. precision = (precision * 59 + 195) / 196;
  9462. Value.toString(PrettySourceValue, precision);
  9463. SmallString<16> PrettyTargetValue;
  9464. if (IsBool)
  9465. PrettyTargetValue = Value.isZero() ? "false" : "true";
  9466. else
  9467. IntegerValue.toString(PrettyTargetValue);
  9468. if (PruneWarnings) {
  9469. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9470. S.PDiag(DiagID)
  9471. << E->getType() << T.getUnqualifiedType()
  9472. << PrettySourceValue << PrettyTargetValue
  9473. << E->getSourceRange() << SourceRange(CContext));
  9474. } else {
  9475. S.Diag(E->getExprLoc(), DiagID)
  9476. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  9477. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  9478. }
  9479. }
  9480. /// Analyze the given compound assignment for the possible losing of
  9481. /// floating-point precision.
  9482. static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
  9483. assert(isa<CompoundAssignOperator>(E) &&
  9484. "Must be compound assignment operation");
  9485. // Recurse on the LHS and RHS in here
  9486. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  9487. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  9488. if (E->getLHS()->getType()->isAtomicType())
  9489. S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
  9490. // Now check the outermost expression
  9491. const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
  9492. const auto *RBT = cast<CompoundAssignOperator>(E)
  9493. ->getComputationResultType()
  9494. ->getAs<BuiltinType>();
  9495. // The below checks assume source is floating point.
  9496. if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
  9497. // If source is floating point but target is not.
  9498. if (!ResultBT->isFloatingPoint())
  9499. return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
  9500. E->getExprLoc());
  9501. // If both source and target are floating points.
  9502. // Builtin FP kinds are ordered by increasing FP rank.
  9503. if (ResultBT->getKind() < RBT->getKind() &&
  9504. // We don't want to warn for system macro.
  9505. !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
  9506. // warn about dropping FP rank.
  9507. DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
  9508. diag::warn_impcast_float_result_precision);
  9509. }
  9510. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  9511. IntRange Range) {
  9512. if (!Range.Width) return "0";
  9513. llvm::APSInt ValueInRange = Value;
  9514. ValueInRange.setIsSigned(!Range.NonNegative);
  9515. ValueInRange = ValueInRange.trunc(Range.Width);
  9516. return ValueInRange.toString(10);
  9517. }
  9518. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  9519. if (!isa<ImplicitCastExpr>(Ex))
  9520. return false;
  9521. Expr *InnerE = Ex->IgnoreParenImpCasts();
  9522. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  9523. const Type *Source =
  9524. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  9525. if (Target->isDependentType())
  9526. return false;
  9527. const BuiltinType *FloatCandidateBT =
  9528. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  9529. const Type *BoolCandidateType = ToBool ? Target : Source;
  9530. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  9531. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  9532. }
  9533. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  9534. SourceLocation CC) {
  9535. unsigned NumArgs = TheCall->getNumArgs();
  9536. for (unsigned i = 0; i < NumArgs; ++i) {
  9537. Expr *CurrA = TheCall->getArg(i);
  9538. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  9539. continue;
  9540. bool IsSwapped = ((i > 0) &&
  9541. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  9542. IsSwapped |= ((i < (NumArgs - 1)) &&
  9543. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  9544. if (IsSwapped) {
  9545. // Warn on this floating-point to bool conversion.
  9546. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  9547. CurrA->getType(), CC,
  9548. diag::warn_impcast_floating_point_to_bool);
  9549. }
  9550. }
  9551. }
  9552. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  9553. SourceLocation CC) {
  9554. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  9555. E->getExprLoc()))
  9556. return;
  9557. // Don't warn on functions which have return type nullptr_t.
  9558. if (isa<CallExpr>(E))
  9559. return;
  9560. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  9561. const Expr::NullPointerConstantKind NullKind =
  9562. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  9563. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  9564. return;
  9565. // Return if target type is a safe conversion.
  9566. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  9567. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  9568. return;
  9569. SourceLocation Loc = E->getSourceRange().getBegin();
  9570. // Venture through the macro stacks to get to the source of macro arguments.
  9571. // The new location is a better location than the complete location that was
  9572. // passed in.
  9573. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  9574. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  9575. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  9576. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  9577. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  9578. Loc, S.SourceMgr, S.getLangOpts());
  9579. if (MacroName == "NULL")
  9580. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
  9581. }
  9582. // Only warn if the null and context location are in the same macro expansion.
  9583. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  9584. return;
  9585. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  9586. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  9587. << FixItHint::CreateReplacement(Loc,
  9588. S.getFixItZeroLiteralForType(T, Loc));
  9589. }
  9590. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9591. ObjCArrayLiteral *ArrayLiteral);
  9592. static void
  9593. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9594. ObjCDictionaryLiteral *DictionaryLiteral);
  9595. /// Check a single element within a collection literal against the
  9596. /// target element type.
  9597. static void checkObjCCollectionLiteralElement(Sema &S,
  9598. QualType TargetElementType,
  9599. Expr *Element,
  9600. unsigned ElementKind) {
  9601. // Skip a bitcast to 'id' or qualified 'id'.
  9602. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  9603. if (ICE->getCastKind() == CK_BitCast &&
  9604. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  9605. Element = ICE->getSubExpr();
  9606. }
  9607. QualType ElementType = Element->getType();
  9608. ExprResult ElementResult(Element);
  9609. if (ElementType->getAs<ObjCObjectPointerType>() &&
  9610. S.CheckSingleAssignmentConstraints(TargetElementType,
  9611. ElementResult,
  9612. false, false)
  9613. != Sema::Compatible) {
  9614. S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
  9615. << ElementType << ElementKind << TargetElementType
  9616. << Element->getSourceRange();
  9617. }
  9618. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  9619. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  9620. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  9621. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  9622. }
  9623. /// Check an Objective-C array literal being converted to the given
  9624. /// target type.
  9625. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  9626. ObjCArrayLiteral *ArrayLiteral) {
  9627. if (!S.NSArrayDecl)
  9628. return;
  9629. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9630. if (!TargetObjCPtr)
  9631. return;
  9632. if (TargetObjCPtr->isUnspecialized() ||
  9633. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9634. != S.NSArrayDecl->getCanonicalDecl())
  9635. return;
  9636. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9637. if (TypeArgs.size() != 1)
  9638. return;
  9639. QualType TargetElementType = TypeArgs[0];
  9640. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  9641. checkObjCCollectionLiteralElement(S, TargetElementType,
  9642. ArrayLiteral->getElement(I),
  9643. 0);
  9644. }
  9645. }
  9646. /// Check an Objective-C dictionary literal being converted to the given
  9647. /// target type.
  9648. static void
  9649. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  9650. ObjCDictionaryLiteral *DictionaryLiteral) {
  9651. if (!S.NSDictionaryDecl)
  9652. return;
  9653. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  9654. if (!TargetObjCPtr)
  9655. return;
  9656. if (TargetObjCPtr->isUnspecialized() ||
  9657. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  9658. != S.NSDictionaryDecl->getCanonicalDecl())
  9659. return;
  9660. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  9661. if (TypeArgs.size() != 2)
  9662. return;
  9663. QualType TargetKeyType = TypeArgs[0];
  9664. QualType TargetObjectType = TypeArgs[1];
  9665. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  9666. auto Element = DictionaryLiteral->getKeyValueElement(I);
  9667. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  9668. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  9669. }
  9670. }
  9671. // Helper function to filter out cases for constant width constant conversion.
  9672. // Don't warn on char array initialization or for non-decimal values.
  9673. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  9674. SourceLocation CC) {
  9675. // If initializing from a constant, and the constant starts with '0',
  9676. // then it is a binary, octal, or hexadecimal. Allow these constants
  9677. // to fill all the bits, even if there is a sign change.
  9678. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  9679. const char FirstLiteralCharacter =
  9680. S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
  9681. if (FirstLiteralCharacter == '0')
  9682. return false;
  9683. }
  9684. // If the CC location points to a '{', and the type is char, then assume
  9685. // assume it is an array initialization.
  9686. if (CC.isValid() && T->isCharType()) {
  9687. const char FirstContextCharacter =
  9688. S.getSourceManager().getCharacterData(CC)[0];
  9689. if (FirstContextCharacter == '{')
  9690. return false;
  9691. }
  9692. return true;
  9693. }
  9694. static void
  9695. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  9696. bool *ICContext = nullptr) {
  9697. if (E->isTypeDependent() || E->isValueDependent()) return;
  9698. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  9699. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  9700. if (Source == Target) return;
  9701. if (Target->isDependentType()) return;
  9702. // If the conversion context location is invalid don't complain. We also
  9703. // don't want to emit a warning if the issue occurs from the expansion of
  9704. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  9705. // delay this check as long as possible. Once we detect we are in that
  9706. // scenario, we just return.
  9707. if (CC.isInvalid())
  9708. return;
  9709. if (Source->isAtomicType())
  9710. S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
  9711. // Diagnose implicit casts to bool.
  9712. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  9713. if (isa<StringLiteral>(E))
  9714. // Warn on string literal to bool. Checks for string literals in logical
  9715. // and expressions, for instance, assert(0 && "error here"), are
  9716. // prevented by a check in AnalyzeImplicitConversions().
  9717. return DiagnoseImpCast(S, E, T, CC,
  9718. diag::warn_impcast_string_literal_to_bool);
  9719. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  9720. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  9721. // This covers the literal expressions that evaluate to Objective-C
  9722. // objects.
  9723. return DiagnoseImpCast(S, E, T, CC,
  9724. diag::warn_impcast_objective_c_literal_to_bool);
  9725. }
  9726. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  9727. // Warn on pointer to bool conversion that is always true.
  9728. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  9729. SourceRange(CC));
  9730. }
  9731. }
  9732. // Check implicit casts from Objective-C collection literals to specialized
  9733. // collection types, e.g., NSArray<NSString *> *.
  9734. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  9735. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  9736. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  9737. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  9738. // Strip vector types.
  9739. if (isa<VectorType>(Source)) {
  9740. if (!isa<VectorType>(Target)) {
  9741. if (S.SourceMgr.isInSystemMacro(CC))
  9742. return;
  9743. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  9744. }
  9745. // If the vector cast is cast between two vectors of the same size, it is
  9746. // a bitcast, not a conversion.
  9747. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  9748. return;
  9749. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  9750. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  9751. }
  9752. if (auto VecTy = dyn_cast<VectorType>(Target))
  9753. Target = VecTy->getElementType().getTypePtr();
  9754. // Strip complex types.
  9755. if (isa<ComplexType>(Source)) {
  9756. if (!isa<ComplexType>(Target)) {
  9757. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  9758. return;
  9759. return DiagnoseImpCast(S, E, T, CC,
  9760. S.getLangOpts().CPlusPlus
  9761. ? diag::err_impcast_complex_scalar
  9762. : diag::warn_impcast_complex_scalar);
  9763. }
  9764. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  9765. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  9766. }
  9767. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  9768. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  9769. // If the source is floating point...
  9770. if (SourceBT && SourceBT->isFloatingPoint()) {
  9771. // ...and the target is floating point...
  9772. if (TargetBT && TargetBT->isFloatingPoint()) {
  9773. // ...then warn if we're dropping FP rank.
  9774. // Builtin FP kinds are ordered by increasing FP rank.
  9775. if (SourceBT->getKind() > TargetBT->getKind()) {
  9776. // Don't warn about float constants that are precisely
  9777. // representable in the target type.
  9778. Expr::EvalResult result;
  9779. if (E->EvaluateAsRValue(result, S.Context)) {
  9780. // Value might be a float, a float vector, or a float complex.
  9781. if (IsSameFloatAfterCast(result.Val,
  9782. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  9783. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  9784. return;
  9785. }
  9786. if (S.SourceMgr.isInSystemMacro(CC))
  9787. return;
  9788. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  9789. }
  9790. // ... or possibly if we're increasing rank, too
  9791. else if (TargetBT->getKind() > SourceBT->getKind()) {
  9792. if (S.SourceMgr.isInSystemMacro(CC))
  9793. return;
  9794. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  9795. }
  9796. return;
  9797. }
  9798. // If the target is integral, always warn.
  9799. if (TargetBT && TargetBT->isInteger()) {
  9800. if (S.SourceMgr.isInSystemMacro(CC))
  9801. return;
  9802. DiagnoseFloatingImpCast(S, E, T, CC);
  9803. }
  9804. // Detect the case where a call result is converted from floating-point to
  9805. // to bool, and the final argument to the call is converted from bool, to
  9806. // discover this typo:
  9807. //
  9808. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  9809. //
  9810. // FIXME: This is an incredibly special case; is there some more general
  9811. // way to detect this class of misplaced-parentheses bug?
  9812. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  9813. // Check last argument of function call to see if it is an
  9814. // implicit cast from a type matching the type the result
  9815. // is being cast to.
  9816. CallExpr *CEx = cast<CallExpr>(E);
  9817. if (unsigned NumArgs = CEx->getNumArgs()) {
  9818. Expr *LastA = CEx->getArg(NumArgs - 1);
  9819. Expr *InnerE = LastA->IgnoreParenImpCasts();
  9820. if (isa<ImplicitCastExpr>(LastA) &&
  9821. InnerE->getType()->isBooleanType()) {
  9822. // Warn on this floating-point to bool conversion
  9823. DiagnoseImpCast(S, E, T, CC,
  9824. diag::warn_impcast_floating_point_to_bool);
  9825. }
  9826. }
  9827. }
  9828. return;
  9829. }
  9830. if (Source->isFixedPointType()) {
  9831. // TODO: Only CK_FixedPointCast is supported now. The other valid casts
  9832. // should be accounted for here.
  9833. if (Target->isFixedPointType()) {
  9834. Expr::EvalResult Result;
  9835. if (E->EvaluateAsFixedPoint(Result, S.Context,
  9836. Expr::SE_AllowSideEffects)) {
  9837. APFixedPoint Value = Result.Val.getFixedPoint();
  9838. APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
  9839. APFixedPoint MinVal = S.Context.getFixedPointMin(T);
  9840. if (Value > MaxVal || Value < MinVal) {
  9841. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9842. S.PDiag(diag::warn_impcast_fixed_point_range)
  9843. << Value.toString() << T
  9844. << E->getSourceRange()
  9845. << clang::SourceRange(CC));
  9846. return;
  9847. }
  9848. }
  9849. }
  9850. }
  9851. DiagnoseNullConversion(S, E, T, CC);
  9852. S.DiscardMisalignedMemberAddress(Target, E);
  9853. if (!Source->isIntegerType() || !Target->isIntegerType())
  9854. return;
  9855. // TODO: remove this early return once the false positives for constant->bool
  9856. // in templates, macros, etc, are reduced or removed.
  9857. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  9858. return;
  9859. IntRange SourceRange = GetExprRange(S.Context, E);
  9860. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  9861. if (SourceRange.Width > TargetRange.Width) {
  9862. // If the source is a constant, use a default-on diagnostic.
  9863. // TODO: this should happen for bitfield stores, too.
  9864. Expr::EvalResult Result;
  9865. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
  9866. llvm::APSInt Value(32);
  9867. Value = Result.Val.getInt();
  9868. if (S.SourceMgr.isInSystemMacro(CC))
  9869. return;
  9870. std::string PrettySourceValue = Value.toString(10);
  9871. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9872. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  9873. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9874. << PrettySourceValue << PrettyTargetValue
  9875. << E->getType() << T << E->getSourceRange()
  9876. << clang::SourceRange(CC));
  9877. return;
  9878. }
  9879. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  9880. if (S.SourceMgr.isInSystemMacro(CC))
  9881. return;
  9882. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  9883. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  9884. /* pruneControlFlow */ true);
  9885. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  9886. }
  9887. if (TargetRange.Width > SourceRange.Width) {
  9888. if (auto *UO = dyn_cast<UnaryOperator>(E))
  9889. if (UO->getOpcode() == UO_Minus)
  9890. if (Source->isUnsignedIntegerType()) {
  9891. if (Target->isUnsignedIntegerType())
  9892. return DiagnoseImpCast(S, E, T, CC,
  9893. diag::warn_impcast_high_order_zero_bits);
  9894. if (Target->isSignedIntegerType())
  9895. return DiagnoseImpCast(S, E, T, CC,
  9896. diag::warn_impcast_nonnegative_result);
  9897. }
  9898. }
  9899. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  9900. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  9901. // Warn when doing a signed to signed conversion, warn if the positive
  9902. // source value is exactly the width of the target type, which will
  9903. // cause a negative value to be stored.
  9904. Expr::EvalResult Result;
  9905. if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
  9906. !S.SourceMgr.isInSystemMacro(CC)) {
  9907. llvm::APSInt Value = Result.Val.getInt();
  9908. if (isSameWidthConstantConversion(S, E, T, CC)) {
  9909. std::string PrettySourceValue = Value.toString(10);
  9910. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  9911. S.DiagRuntimeBehavior(
  9912. E->getExprLoc(), E,
  9913. S.PDiag(diag::warn_impcast_integer_precision_constant)
  9914. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  9915. << E->getSourceRange() << clang::SourceRange(CC));
  9916. return;
  9917. }
  9918. }
  9919. // Fall through for non-constants to give a sign conversion warning.
  9920. }
  9921. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  9922. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  9923. SourceRange.Width == TargetRange.Width)) {
  9924. if (S.SourceMgr.isInSystemMacro(CC))
  9925. return;
  9926. unsigned DiagID = diag::warn_impcast_integer_sign;
  9927. // Traditionally, gcc has warned about this under -Wsign-compare.
  9928. // We also want to warn about it in -Wconversion.
  9929. // So if -Wconversion is off, use a completely identical diagnostic
  9930. // in the sign-compare group.
  9931. // The conditional-checking code will
  9932. if (ICContext) {
  9933. DiagID = diag::warn_impcast_integer_sign_conditional;
  9934. *ICContext = true;
  9935. }
  9936. return DiagnoseImpCast(S, E, T, CC, DiagID);
  9937. }
  9938. // Diagnose conversions between different enumeration types.
  9939. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  9940. // type, to give us better diagnostics.
  9941. QualType SourceType = E->getType();
  9942. if (!S.getLangOpts().CPlusPlus) {
  9943. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9944. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  9945. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  9946. SourceType = S.Context.getTypeDeclType(Enum);
  9947. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  9948. }
  9949. }
  9950. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  9951. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  9952. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  9953. TargetEnum->getDecl()->hasNameForLinkage() &&
  9954. SourceEnum != TargetEnum) {
  9955. if (S.SourceMgr.isInSystemMacro(CC))
  9956. return;
  9957. return DiagnoseImpCast(S, E, SourceType, T, CC,
  9958. diag::warn_impcast_different_enum_types);
  9959. }
  9960. }
  9961. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9962. SourceLocation CC, QualType T);
  9963. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  9964. SourceLocation CC, bool &ICContext) {
  9965. E = E->IgnoreParenImpCasts();
  9966. if (isa<ConditionalOperator>(E))
  9967. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  9968. AnalyzeImplicitConversions(S, E, CC);
  9969. if (E->getType() != T)
  9970. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  9971. }
  9972. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  9973. SourceLocation CC, QualType T) {
  9974. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  9975. bool Suspicious = false;
  9976. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  9977. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  9978. // If -Wconversion would have warned about either of the candidates
  9979. // for a signedness conversion to the context type...
  9980. if (!Suspicious) return;
  9981. // ...but it's currently ignored...
  9982. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  9983. return;
  9984. // ...then check whether it would have warned about either of the
  9985. // candidates for a signedness conversion to the condition type.
  9986. if (E->getType() == T) return;
  9987. Suspicious = false;
  9988. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  9989. E->getType(), CC, &Suspicious);
  9990. if (!Suspicious)
  9991. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  9992. E->getType(), CC, &Suspicious);
  9993. }
  9994. /// Check conversion of given expression to boolean.
  9995. /// Input argument E is a logical expression.
  9996. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  9997. if (S.getLangOpts().Bool)
  9998. return;
  9999. if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
  10000. return;
  10001. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  10002. }
  10003. /// AnalyzeImplicitConversions - Find and report any interesting
  10004. /// implicit conversions in the given expression. There are a couple
  10005. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  10006. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  10007. SourceLocation CC) {
  10008. QualType T = OrigE->getType();
  10009. Expr *E = OrigE->IgnoreParenImpCasts();
  10010. if (E->isTypeDependent() || E->isValueDependent())
  10011. return;
  10012. // For conditional operators, we analyze the arguments as if they
  10013. // were being fed directly into the output.
  10014. if (isa<ConditionalOperator>(E)) {
  10015. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  10016. CheckConditionalOperator(S, CO, CC, T);
  10017. return;
  10018. }
  10019. // Check implicit argument conversions for function calls.
  10020. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  10021. CheckImplicitArgumentConversions(S, Call, CC);
  10022. // Go ahead and check any implicit conversions we might have skipped.
  10023. // The non-canonical typecheck is just an optimization;
  10024. // CheckImplicitConversion will filter out dead implicit conversions.
  10025. if (E->getType() != T)
  10026. CheckImplicitConversion(S, E, T, CC);
  10027. // Now continue drilling into this expression.
  10028. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  10029. // The bound subexpressions in a PseudoObjectExpr are not reachable
  10030. // as transitive children.
  10031. // FIXME: Use a more uniform representation for this.
  10032. for (auto *SE : POE->semantics())
  10033. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  10034. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  10035. }
  10036. // Skip past explicit casts.
  10037. if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
  10038. E = CE->getSubExpr()->IgnoreParenImpCasts();
  10039. if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
  10040. S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
  10041. return AnalyzeImplicitConversions(S, E, CC);
  10042. }
  10043. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10044. // Do a somewhat different check with comparison operators.
  10045. if (BO->isComparisonOp())
  10046. return AnalyzeComparison(S, BO);
  10047. // And with simple assignments.
  10048. if (BO->getOpcode() == BO_Assign)
  10049. return AnalyzeAssignment(S, BO);
  10050. // And with compound assignments.
  10051. if (BO->isAssignmentOp())
  10052. return AnalyzeCompoundAssignment(S, BO);
  10053. }
  10054. // These break the otherwise-useful invariant below. Fortunately,
  10055. // we don't really need to recurse into them, because any internal
  10056. // expressions should have been analyzed already when they were
  10057. // built into statements.
  10058. if (isa<StmtExpr>(E)) return;
  10059. // Don't descend into unevaluated contexts.
  10060. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  10061. // Now just recurse over the expression's children.
  10062. CC = E->getExprLoc();
  10063. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  10064. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  10065. for (Stmt *SubStmt : E->children()) {
  10066. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  10067. if (!ChildExpr)
  10068. continue;
  10069. if (IsLogicalAndOperator &&
  10070. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  10071. // Ignore checking string literals that are in logical and operators.
  10072. // This is a common pattern for asserts.
  10073. continue;
  10074. AnalyzeImplicitConversions(S, ChildExpr, CC);
  10075. }
  10076. if (BO && BO->isLogicalOp()) {
  10077. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  10078. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10079. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10080. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  10081. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  10082. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  10083. }
  10084. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
  10085. if (U->getOpcode() == UO_LNot) {
  10086. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  10087. } else if (U->getOpcode() != UO_AddrOf) {
  10088. if (U->getSubExpr()->getType()->isAtomicType())
  10089. S.Diag(U->getSubExpr()->getBeginLoc(),
  10090. diag::warn_atomic_implicit_seq_cst);
  10091. }
  10092. }
  10093. }
  10094. /// Diagnose integer type and any valid implicit conversion to it.
  10095. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  10096. // Taking into account implicit conversions,
  10097. // allow any integer.
  10098. if (!E->getType()->isIntegerType()) {
  10099. S.Diag(E->getBeginLoc(),
  10100. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  10101. return true;
  10102. }
  10103. // Potentially emit standard warnings for implicit conversions if enabled
  10104. // using -Wconversion.
  10105. CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
  10106. return false;
  10107. }
  10108. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  10109. // Returns true when emitting a warning about taking the address of a reference.
  10110. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  10111. const PartialDiagnostic &PD) {
  10112. E = E->IgnoreParenImpCasts();
  10113. const FunctionDecl *FD = nullptr;
  10114. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10115. if (!DRE->getDecl()->getType()->isReferenceType())
  10116. return false;
  10117. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10118. if (!M->getMemberDecl()->getType()->isReferenceType())
  10119. return false;
  10120. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  10121. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  10122. return false;
  10123. FD = Call->getDirectCallee();
  10124. } else {
  10125. return false;
  10126. }
  10127. SemaRef.Diag(E->getExprLoc(), PD);
  10128. // If possible, point to location of function.
  10129. if (FD) {
  10130. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  10131. }
  10132. return true;
  10133. }
  10134. // Returns true if the SourceLocation is expanded from any macro body.
  10135. // Returns false if the SourceLocation is invalid, is from not in a macro
  10136. // expansion, or is from expanded from a top-level macro argument.
  10137. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  10138. if (Loc.isInvalid())
  10139. return false;
  10140. while (Loc.isMacroID()) {
  10141. if (SM.isMacroBodyExpansion(Loc))
  10142. return true;
  10143. Loc = SM.getImmediateMacroCallerLoc(Loc);
  10144. }
  10145. return false;
  10146. }
  10147. /// Diagnose pointers that are always non-null.
  10148. /// \param E the expression containing the pointer
  10149. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  10150. /// compared to a null pointer
  10151. /// \param IsEqual True when the comparison is equal to a null pointer
  10152. /// \param Range Extra SourceRange to highlight in the diagnostic
  10153. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  10154. Expr::NullPointerConstantKind NullKind,
  10155. bool IsEqual, SourceRange Range) {
  10156. if (!E)
  10157. return;
  10158. // Don't warn inside macros.
  10159. if (E->getExprLoc().isMacroID()) {
  10160. const SourceManager &SM = getSourceManager();
  10161. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  10162. IsInAnyMacroBody(SM, Range.getBegin()))
  10163. return;
  10164. }
  10165. E = E->IgnoreImpCasts();
  10166. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  10167. if (isa<CXXThisExpr>(E)) {
  10168. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  10169. : diag::warn_this_bool_conversion;
  10170. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  10171. return;
  10172. }
  10173. bool IsAddressOf = false;
  10174. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10175. if (UO->getOpcode() != UO_AddrOf)
  10176. return;
  10177. IsAddressOf = true;
  10178. E = UO->getSubExpr();
  10179. }
  10180. if (IsAddressOf) {
  10181. unsigned DiagID = IsCompare
  10182. ? diag::warn_address_of_reference_null_compare
  10183. : diag::warn_address_of_reference_bool_conversion;
  10184. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  10185. << IsEqual;
  10186. if (CheckForReference(*this, E, PD)) {
  10187. return;
  10188. }
  10189. }
  10190. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  10191. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  10192. std::string Str;
  10193. llvm::raw_string_ostream S(Str);
  10194. E->printPretty(S, nullptr, getPrintingPolicy());
  10195. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  10196. : diag::warn_cast_nonnull_to_bool;
  10197. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  10198. << E->getSourceRange() << Range << IsEqual;
  10199. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  10200. };
  10201. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  10202. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  10203. if (auto *Callee = Call->getDirectCallee()) {
  10204. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  10205. ComplainAboutNonnullParamOrCall(A);
  10206. return;
  10207. }
  10208. }
  10209. }
  10210. // Expect to find a single Decl. Skip anything more complicated.
  10211. ValueDecl *D = nullptr;
  10212. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  10213. D = R->getDecl();
  10214. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  10215. D = M->getMemberDecl();
  10216. }
  10217. // Weak Decls can be null.
  10218. if (!D || D->isWeak())
  10219. return;
  10220. // Check for parameter decl with nonnull attribute
  10221. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  10222. if (getCurFunction() &&
  10223. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  10224. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  10225. ComplainAboutNonnullParamOrCall(A);
  10226. return;
  10227. }
  10228. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  10229. auto ParamIter = llvm::find(FD->parameters(), PV);
  10230. assert(ParamIter != FD->param_end());
  10231. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  10232. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  10233. if (!NonNull->args_size()) {
  10234. ComplainAboutNonnullParamOrCall(NonNull);
  10235. return;
  10236. }
  10237. for (const ParamIdx &ArgNo : NonNull->args()) {
  10238. if (ArgNo.getASTIndex() == ParamNo) {
  10239. ComplainAboutNonnullParamOrCall(NonNull);
  10240. return;
  10241. }
  10242. }
  10243. }
  10244. }
  10245. }
  10246. }
  10247. QualType T = D->getType();
  10248. const bool IsArray = T->isArrayType();
  10249. const bool IsFunction = T->isFunctionType();
  10250. // Address of function is used to silence the function warning.
  10251. if (IsAddressOf && IsFunction) {
  10252. return;
  10253. }
  10254. // Found nothing.
  10255. if (!IsAddressOf && !IsFunction && !IsArray)
  10256. return;
  10257. // Pretty print the expression for the diagnostic.
  10258. std::string Str;
  10259. llvm::raw_string_ostream S(Str);
  10260. E->printPretty(S, nullptr, getPrintingPolicy());
  10261. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  10262. : diag::warn_impcast_pointer_to_bool;
  10263. enum {
  10264. AddressOf,
  10265. FunctionPointer,
  10266. ArrayPointer
  10267. } DiagType;
  10268. if (IsAddressOf)
  10269. DiagType = AddressOf;
  10270. else if (IsFunction)
  10271. DiagType = FunctionPointer;
  10272. else if (IsArray)
  10273. DiagType = ArrayPointer;
  10274. else
  10275. llvm_unreachable("Could not determine diagnostic.");
  10276. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  10277. << Range << IsEqual;
  10278. if (!IsFunction)
  10279. return;
  10280. // Suggest '&' to silence the function warning.
  10281. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  10282. << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
  10283. // Check to see if '()' fixit should be emitted.
  10284. QualType ReturnType;
  10285. UnresolvedSet<4> NonTemplateOverloads;
  10286. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  10287. if (ReturnType.isNull())
  10288. return;
  10289. if (IsCompare) {
  10290. // There are two cases here. If there is null constant, the only suggest
  10291. // for a pointer return type. If the null is 0, then suggest if the return
  10292. // type is a pointer or an integer type.
  10293. if (!ReturnType->isPointerType()) {
  10294. if (NullKind == Expr::NPCK_ZeroExpression ||
  10295. NullKind == Expr::NPCK_ZeroLiteral) {
  10296. if (!ReturnType->isIntegerType())
  10297. return;
  10298. } else {
  10299. return;
  10300. }
  10301. }
  10302. } else { // !IsCompare
  10303. // For function to bool, only suggest if the function pointer has bool
  10304. // return type.
  10305. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  10306. return;
  10307. }
  10308. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  10309. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
  10310. }
  10311. /// Diagnoses "dangerous" implicit conversions within the given
  10312. /// expression (which is a full expression). Implements -Wconversion
  10313. /// and -Wsign-compare.
  10314. ///
  10315. /// \param CC the "context" location of the implicit conversion, i.e.
  10316. /// the most location of the syntactic entity requiring the implicit
  10317. /// conversion
  10318. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  10319. // Don't diagnose in unevaluated contexts.
  10320. if (isUnevaluatedContext())
  10321. return;
  10322. // Don't diagnose for value- or type-dependent expressions.
  10323. if (E->isTypeDependent() || E->isValueDependent())
  10324. return;
  10325. // Check for array bounds violations in cases where the check isn't triggered
  10326. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  10327. // ArraySubscriptExpr is on the RHS of a variable initialization.
  10328. CheckArrayAccess(E);
  10329. // This is not the right CC for (e.g.) a variable initialization.
  10330. AnalyzeImplicitConversions(*this, E, CC);
  10331. }
  10332. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  10333. /// Input argument E is a logical expression.
  10334. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  10335. ::CheckBoolLikeConversion(*this, E, CC);
  10336. }
  10337. /// Diagnose when expression is an integer constant expression and its evaluation
  10338. /// results in integer overflow
  10339. void Sema::CheckForIntOverflow (Expr *E) {
  10340. // Use a work list to deal with nested struct initializers.
  10341. SmallVector<Expr *, 2> Exprs(1, E);
  10342. do {
  10343. Expr *OriginalE = Exprs.pop_back_val();
  10344. Expr *E = OriginalE->IgnoreParenCasts();
  10345. if (isa<BinaryOperator>(E)) {
  10346. E->EvaluateForOverflow(Context);
  10347. continue;
  10348. }
  10349. if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
  10350. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  10351. else if (isa<ObjCBoxedExpr>(OriginalE))
  10352. E->EvaluateForOverflow(Context);
  10353. else if (auto Call = dyn_cast<CallExpr>(E))
  10354. Exprs.append(Call->arg_begin(), Call->arg_end());
  10355. else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
  10356. Exprs.append(Message->arg_begin(), Message->arg_end());
  10357. } while (!Exprs.empty());
  10358. }
  10359. namespace {
  10360. /// Visitor for expressions which looks for unsequenced operations on the
  10361. /// same object.
  10362. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  10363. using Base = EvaluatedExprVisitor<SequenceChecker>;
  10364. /// A tree of sequenced regions within an expression. Two regions are
  10365. /// unsequenced if one is an ancestor or a descendent of the other. When we
  10366. /// finish processing an expression with sequencing, such as a comma
  10367. /// expression, we fold its tree nodes into its parent, since they are
  10368. /// unsequenced with respect to nodes we will visit later.
  10369. class SequenceTree {
  10370. struct Value {
  10371. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  10372. unsigned Parent : 31;
  10373. unsigned Merged : 1;
  10374. };
  10375. SmallVector<Value, 8> Values;
  10376. public:
  10377. /// A region within an expression which may be sequenced with respect
  10378. /// to some other region.
  10379. class Seq {
  10380. friend class SequenceTree;
  10381. unsigned Index;
  10382. explicit Seq(unsigned N) : Index(N) {}
  10383. public:
  10384. Seq() : Index(0) {}
  10385. };
  10386. SequenceTree() { Values.push_back(Value(0)); }
  10387. Seq root() const { return Seq(0); }
  10388. /// Create a new sequence of operations, which is an unsequenced
  10389. /// subset of \p Parent. This sequence of operations is sequenced with
  10390. /// respect to other children of \p Parent.
  10391. Seq allocate(Seq Parent) {
  10392. Values.push_back(Value(Parent.Index));
  10393. return Seq(Values.size() - 1);
  10394. }
  10395. /// Merge a sequence of operations into its parent.
  10396. void merge(Seq S) {
  10397. Values[S.Index].Merged = true;
  10398. }
  10399. /// Determine whether two operations are unsequenced. This operation
  10400. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  10401. /// should have been merged into its parent as appropriate.
  10402. bool isUnsequenced(Seq Cur, Seq Old) {
  10403. unsigned C = representative(Cur.Index);
  10404. unsigned Target = representative(Old.Index);
  10405. while (C >= Target) {
  10406. if (C == Target)
  10407. return true;
  10408. C = Values[C].Parent;
  10409. }
  10410. return false;
  10411. }
  10412. private:
  10413. /// Pick a representative for a sequence.
  10414. unsigned representative(unsigned K) {
  10415. if (Values[K].Merged)
  10416. // Perform path compression as we go.
  10417. return Values[K].Parent = representative(Values[K].Parent);
  10418. return K;
  10419. }
  10420. };
  10421. /// An object for which we can track unsequenced uses.
  10422. using Object = NamedDecl *;
  10423. /// Different flavors of object usage which we track. We only track the
  10424. /// least-sequenced usage of each kind.
  10425. enum UsageKind {
  10426. /// A read of an object. Multiple unsequenced reads are OK.
  10427. UK_Use,
  10428. /// A modification of an object which is sequenced before the value
  10429. /// computation of the expression, such as ++n in C++.
  10430. UK_ModAsValue,
  10431. /// A modification of an object which is not sequenced before the value
  10432. /// computation of the expression, such as n++.
  10433. UK_ModAsSideEffect,
  10434. UK_Count = UK_ModAsSideEffect + 1
  10435. };
  10436. struct Usage {
  10437. Expr *Use;
  10438. SequenceTree::Seq Seq;
  10439. Usage() : Use(nullptr), Seq() {}
  10440. };
  10441. struct UsageInfo {
  10442. Usage Uses[UK_Count];
  10443. /// Have we issued a diagnostic for this variable already?
  10444. bool Diagnosed;
  10445. UsageInfo() : Uses(), Diagnosed(false) {}
  10446. };
  10447. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  10448. Sema &SemaRef;
  10449. /// Sequenced regions within the expression.
  10450. SequenceTree Tree;
  10451. /// Declaration modifications and references which we have seen.
  10452. UsageInfoMap UsageMap;
  10453. /// The region we are currently within.
  10454. SequenceTree::Seq Region;
  10455. /// Filled in with declarations which were modified as a side-effect
  10456. /// (that is, post-increment operations).
  10457. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  10458. /// Expressions to check later. We defer checking these to reduce
  10459. /// stack usage.
  10460. SmallVectorImpl<Expr *> &WorkList;
  10461. /// RAII object wrapping the visitation of a sequenced subexpression of an
  10462. /// expression. At the end of this process, the side-effects of the evaluation
  10463. /// become sequenced with respect to the value computation of the result, so
  10464. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  10465. /// UK_ModAsValue.
  10466. struct SequencedSubexpression {
  10467. SequencedSubexpression(SequenceChecker &Self)
  10468. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  10469. Self.ModAsSideEffect = &ModAsSideEffect;
  10470. }
  10471. ~SequencedSubexpression() {
  10472. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  10473. UsageInfo &U = Self.UsageMap[M.first];
  10474. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  10475. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  10476. SideEffectUsage = M.second;
  10477. }
  10478. Self.ModAsSideEffect = OldModAsSideEffect;
  10479. }
  10480. SequenceChecker &Self;
  10481. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  10482. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  10483. };
  10484. /// RAII object wrapping the visitation of a subexpression which we might
  10485. /// choose to evaluate as a constant. If any subexpression is evaluated and
  10486. /// found to be non-constant, this allows us to suppress the evaluation of
  10487. /// the outer expression.
  10488. class EvaluationTracker {
  10489. public:
  10490. EvaluationTracker(SequenceChecker &Self)
  10491. : Self(Self), Prev(Self.EvalTracker) {
  10492. Self.EvalTracker = this;
  10493. }
  10494. ~EvaluationTracker() {
  10495. Self.EvalTracker = Prev;
  10496. if (Prev)
  10497. Prev->EvalOK &= EvalOK;
  10498. }
  10499. bool evaluate(const Expr *E, bool &Result) {
  10500. if (!EvalOK || E->isValueDependent())
  10501. return false;
  10502. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  10503. return EvalOK;
  10504. }
  10505. private:
  10506. SequenceChecker &Self;
  10507. EvaluationTracker *Prev;
  10508. bool EvalOK = true;
  10509. } *EvalTracker = nullptr;
  10510. /// Find the object which is produced by the specified expression,
  10511. /// if any.
  10512. Object getObject(Expr *E, bool Mod) const {
  10513. E = E->IgnoreParenCasts();
  10514. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  10515. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  10516. return getObject(UO->getSubExpr(), Mod);
  10517. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10518. if (BO->getOpcode() == BO_Comma)
  10519. return getObject(BO->getRHS(), Mod);
  10520. if (Mod && BO->isAssignmentOp())
  10521. return getObject(BO->getLHS(), Mod);
  10522. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10523. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  10524. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  10525. return ME->getMemberDecl();
  10526. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10527. // FIXME: If this is a reference, map through to its value.
  10528. return DRE->getDecl();
  10529. return nullptr;
  10530. }
  10531. /// Note that an object was modified or used by an expression.
  10532. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  10533. Usage &U = UI.Uses[UK];
  10534. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  10535. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  10536. ModAsSideEffect->push_back(std::make_pair(O, U));
  10537. U.Use = Ref;
  10538. U.Seq = Region;
  10539. }
  10540. }
  10541. /// Check whether a modification or use conflicts with a prior usage.
  10542. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  10543. bool IsModMod) {
  10544. if (UI.Diagnosed)
  10545. return;
  10546. const Usage &U = UI.Uses[OtherKind];
  10547. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  10548. return;
  10549. Expr *Mod = U.Use;
  10550. Expr *ModOrUse = Ref;
  10551. if (OtherKind == UK_Use)
  10552. std::swap(Mod, ModOrUse);
  10553. SemaRef.Diag(Mod->getExprLoc(),
  10554. IsModMod ? diag::warn_unsequenced_mod_mod
  10555. : diag::warn_unsequenced_mod_use)
  10556. << O << SourceRange(ModOrUse->getExprLoc());
  10557. UI.Diagnosed = true;
  10558. }
  10559. void notePreUse(Object O, Expr *Use) {
  10560. UsageInfo &U = UsageMap[O];
  10561. // Uses conflict with other modifications.
  10562. checkUsage(O, U, Use, UK_ModAsValue, false);
  10563. }
  10564. void notePostUse(Object O, Expr *Use) {
  10565. UsageInfo &U = UsageMap[O];
  10566. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  10567. addUsage(U, O, Use, UK_Use);
  10568. }
  10569. void notePreMod(Object O, Expr *Mod) {
  10570. UsageInfo &U = UsageMap[O];
  10571. // Modifications conflict with other modifications and with uses.
  10572. checkUsage(O, U, Mod, UK_ModAsValue, true);
  10573. checkUsage(O, U, Mod, UK_Use, false);
  10574. }
  10575. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  10576. UsageInfo &U = UsageMap[O];
  10577. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  10578. addUsage(U, O, Use, UK);
  10579. }
  10580. public:
  10581. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  10582. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  10583. Visit(E);
  10584. }
  10585. void VisitStmt(Stmt *S) {
  10586. // Skip all statements which aren't expressions for now.
  10587. }
  10588. void VisitExpr(Expr *E) {
  10589. // By default, just recurse to evaluated subexpressions.
  10590. Base::VisitStmt(E);
  10591. }
  10592. void VisitCastExpr(CastExpr *E) {
  10593. Object O = Object();
  10594. if (E->getCastKind() == CK_LValueToRValue)
  10595. O = getObject(E->getSubExpr(), false);
  10596. if (O)
  10597. notePreUse(O, E);
  10598. VisitExpr(E);
  10599. if (O)
  10600. notePostUse(O, E);
  10601. }
  10602. void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
  10603. SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
  10604. SequenceTree::Seq AfterRegion = Tree.allocate(Region);
  10605. SequenceTree::Seq OldRegion = Region;
  10606. {
  10607. SequencedSubexpression SeqBefore(*this);
  10608. Region = BeforeRegion;
  10609. Visit(SequencedBefore);
  10610. }
  10611. Region = AfterRegion;
  10612. Visit(SequencedAfter);
  10613. Region = OldRegion;
  10614. Tree.merge(BeforeRegion);
  10615. Tree.merge(AfterRegion);
  10616. }
  10617. void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
  10618. // C++17 [expr.sub]p1:
  10619. // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
  10620. // expression E1 is sequenced before the expression E2.
  10621. if (SemaRef.getLangOpts().CPlusPlus17)
  10622. VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
  10623. else
  10624. Base::VisitStmt(ASE);
  10625. }
  10626. void VisitBinComma(BinaryOperator *BO) {
  10627. // C++11 [expr.comma]p1:
  10628. // Every value computation and side effect associated with the left
  10629. // expression is sequenced before every value computation and side
  10630. // effect associated with the right expression.
  10631. VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
  10632. }
  10633. void VisitBinAssign(BinaryOperator *BO) {
  10634. // The modification is sequenced after the value computation of the LHS
  10635. // and RHS, so check it before inspecting the operands and update the
  10636. // map afterwards.
  10637. Object O = getObject(BO->getLHS(), true);
  10638. if (!O)
  10639. return VisitExpr(BO);
  10640. notePreMod(O, BO);
  10641. // C++11 [expr.ass]p7:
  10642. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  10643. // only once.
  10644. //
  10645. // Therefore, for a compound assignment operator, O is considered used
  10646. // everywhere except within the evaluation of E1 itself.
  10647. if (isa<CompoundAssignOperator>(BO))
  10648. notePreUse(O, BO);
  10649. Visit(BO->getLHS());
  10650. if (isa<CompoundAssignOperator>(BO))
  10651. notePostUse(O, BO);
  10652. Visit(BO->getRHS());
  10653. // C++11 [expr.ass]p1:
  10654. // the assignment is sequenced [...] before the value computation of the
  10655. // assignment expression.
  10656. // C11 6.5.16/3 has no such rule.
  10657. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10658. : UK_ModAsSideEffect);
  10659. }
  10660. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  10661. VisitBinAssign(CAO);
  10662. }
  10663. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10664. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  10665. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  10666. Object O = getObject(UO->getSubExpr(), true);
  10667. if (!O)
  10668. return VisitExpr(UO);
  10669. notePreMod(O, UO);
  10670. Visit(UO->getSubExpr());
  10671. // C++11 [expr.pre.incr]p1:
  10672. // the expression ++x is equivalent to x+=1
  10673. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  10674. : UK_ModAsSideEffect);
  10675. }
  10676. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10677. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  10678. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  10679. Object O = getObject(UO->getSubExpr(), true);
  10680. if (!O)
  10681. return VisitExpr(UO);
  10682. notePreMod(O, UO);
  10683. Visit(UO->getSubExpr());
  10684. notePostMod(O, UO, UK_ModAsSideEffect);
  10685. }
  10686. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  10687. void VisitBinLOr(BinaryOperator *BO) {
  10688. // The side-effects of the LHS of an '&&' are sequenced before the
  10689. // value computation of the RHS, and hence before the value computation
  10690. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  10691. // as if they were unconditionally sequenced.
  10692. EvaluationTracker Eval(*this);
  10693. {
  10694. SequencedSubexpression Sequenced(*this);
  10695. Visit(BO->getLHS());
  10696. }
  10697. bool Result;
  10698. if (Eval.evaluate(BO->getLHS(), Result)) {
  10699. if (!Result)
  10700. Visit(BO->getRHS());
  10701. } else {
  10702. // Check for unsequenced operations in the RHS, treating it as an
  10703. // entirely separate evaluation.
  10704. //
  10705. // FIXME: If there are operations in the RHS which are unsequenced
  10706. // with respect to operations outside the RHS, and those operations
  10707. // are unconditionally evaluated, diagnose them.
  10708. WorkList.push_back(BO->getRHS());
  10709. }
  10710. }
  10711. void VisitBinLAnd(BinaryOperator *BO) {
  10712. EvaluationTracker Eval(*this);
  10713. {
  10714. SequencedSubexpression Sequenced(*this);
  10715. Visit(BO->getLHS());
  10716. }
  10717. bool Result;
  10718. if (Eval.evaluate(BO->getLHS(), Result)) {
  10719. if (Result)
  10720. Visit(BO->getRHS());
  10721. } else {
  10722. WorkList.push_back(BO->getRHS());
  10723. }
  10724. }
  10725. // Only visit the condition, unless we can be sure which subexpression will
  10726. // be chosen.
  10727. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  10728. EvaluationTracker Eval(*this);
  10729. {
  10730. SequencedSubexpression Sequenced(*this);
  10731. Visit(CO->getCond());
  10732. }
  10733. bool Result;
  10734. if (Eval.evaluate(CO->getCond(), Result))
  10735. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  10736. else {
  10737. WorkList.push_back(CO->getTrueExpr());
  10738. WorkList.push_back(CO->getFalseExpr());
  10739. }
  10740. }
  10741. void VisitCallExpr(CallExpr *CE) {
  10742. // C++11 [intro.execution]p15:
  10743. // When calling a function [...], every value computation and side effect
  10744. // associated with any argument expression, or with the postfix expression
  10745. // designating the called function, is sequenced before execution of every
  10746. // expression or statement in the body of the function [and thus before
  10747. // the value computation of its result].
  10748. SequencedSubexpression Sequenced(*this);
  10749. Base::VisitCallExpr(CE);
  10750. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  10751. }
  10752. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  10753. // This is a call, so all subexpressions are sequenced before the result.
  10754. SequencedSubexpression Sequenced(*this);
  10755. if (!CCE->isListInitialization())
  10756. return VisitExpr(CCE);
  10757. // In C++11, list initializations are sequenced.
  10758. SmallVector<SequenceTree::Seq, 32> Elts;
  10759. SequenceTree::Seq Parent = Region;
  10760. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  10761. E = CCE->arg_end();
  10762. I != E; ++I) {
  10763. Region = Tree.allocate(Parent);
  10764. Elts.push_back(Region);
  10765. Visit(*I);
  10766. }
  10767. // Forget that the initializers are sequenced.
  10768. Region = Parent;
  10769. for (unsigned I = 0; I < Elts.size(); ++I)
  10770. Tree.merge(Elts[I]);
  10771. }
  10772. void VisitInitListExpr(InitListExpr *ILE) {
  10773. if (!SemaRef.getLangOpts().CPlusPlus11)
  10774. return VisitExpr(ILE);
  10775. // In C++11, list initializations are sequenced.
  10776. SmallVector<SequenceTree::Seq, 32> Elts;
  10777. SequenceTree::Seq Parent = Region;
  10778. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  10779. Expr *E = ILE->getInit(I);
  10780. if (!E) continue;
  10781. Region = Tree.allocate(Parent);
  10782. Elts.push_back(Region);
  10783. Visit(E);
  10784. }
  10785. // Forget that the initializers are sequenced.
  10786. Region = Parent;
  10787. for (unsigned I = 0; I < Elts.size(); ++I)
  10788. Tree.merge(Elts[I]);
  10789. }
  10790. };
  10791. } // namespace
  10792. void Sema::CheckUnsequencedOperations(Expr *E) {
  10793. SmallVector<Expr *, 8> WorkList;
  10794. WorkList.push_back(E);
  10795. while (!WorkList.empty()) {
  10796. Expr *Item = WorkList.pop_back_val();
  10797. SequenceChecker(*this, Item, WorkList);
  10798. }
  10799. }
  10800. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  10801. bool IsConstexpr) {
  10802. CheckImplicitConversions(E, CheckLoc);
  10803. if (!E->isInstantiationDependent())
  10804. CheckUnsequencedOperations(E);
  10805. if (!IsConstexpr && !E->isValueDependent())
  10806. CheckForIntOverflow(E);
  10807. DiagnoseMisalignedMembers();
  10808. }
  10809. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  10810. FieldDecl *BitField,
  10811. Expr *Init) {
  10812. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  10813. }
  10814. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  10815. SourceLocation Loc) {
  10816. if (!PType->isVariablyModifiedType())
  10817. return;
  10818. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  10819. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  10820. return;
  10821. }
  10822. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  10823. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  10824. return;
  10825. }
  10826. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  10827. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  10828. return;
  10829. }
  10830. const ArrayType *AT = S.Context.getAsArrayType(PType);
  10831. if (!AT)
  10832. return;
  10833. if (AT->getSizeModifier() != ArrayType::Star) {
  10834. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  10835. return;
  10836. }
  10837. S.Diag(Loc, diag::err_array_star_in_function_definition);
  10838. }
  10839. /// CheckParmsForFunctionDef - Check that the parameters of the given
  10840. /// function are appropriate for the definition of a function. This
  10841. /// takes care of any checks that cannot be performed on the
  10842. /// declaration itself, e.g., that the types of each of the function
  10843. /// parameters are complete.
  10844. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  10845. bool CheckParameterNames) {
  10846. bool HasInvalidParm = false;
  10847. for (ParmVarDecl *Param : Parameters) {
  10848. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  10849. // function declarator that is part of a function definition of
  10850. // that function shall not have incomplete type.
  10851. //
  10852. // This is also C++ [dcl.fct]p6.
  10853. if (!Param->isInvalidDecl() &&
  10854. RequireCompleteType(Param->getLocation(), Param->getType(),
  10855. diag::err_typecheck_decl_incomplete_type)) {
  10856. Param->setInvalidDecl();
  10857. HasInvalidParm = true;
  10858. }
  10859. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  10860. // declaration of each parameter shall include an identifier.
  10861. if (CheckParameterNames &&
  10862. Param->getIdentifier() == nullptr &&
  10863. !Param->isImplicit() &&
  10864. !getLangOpts().CPlusPlus)
  10865. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10866. // C99 6.7.5.3p12:
  10867. // If the function declarator is not part of a definition of that
  10868. // function, parameters may have incomplete type and may use the [*]
  10869. // notation in their sequences of declarator specifiers to specify
  10870. // variable length array types.
  10871. QualType PType = Param->getOriginalType();
  10872. // FIXME: This diagnostic should point the '[*]' if source-location
  10873. // information is added for it.
  10874. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  10875. // If the parameter is a c++ class type and it has to be destructed in the
  10876. // callee function, declare the destructor so that it can be called by the
  10877. // callee function. Do not perform any direct access check on the dtor here.
  10878. if (!Param->isInvalidDecl()) {
  10879. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  10880. if (!ClassDecl->isInvalidDecl() &&
  10881. !ClassDecl->hasIrrelevantDestructor() &&
  10882. !ClassDecl->isDependentContext() &&
  10883. ClassDecl->isParamDestroyedInCallee()) {
  10884. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  10885. MarkFunctionReferenced(Param->getLocation(), Destructor);
  10886. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  10887. }
  10888. }
  10889. }
  10890. // Parameters with the pass_object_size attribute only need to be marked
  10891. // constant at function definitions. Because we lack information about
  10892. // whether we're on a declaration or definition when we're instantiating the
  10893. // attribute, we need to check for constness here.
  10894. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  10895. if (!Param->getType().isConstQualified())
  10896. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  10897. << Attr->getSpelling() << 1;
  10898. // Check for parameter names shadowing fields from the class.
  10899. if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
  10900. // The owning context for the parameter should be the function, but we
  10901. // want to see if this function's declaration context is a record.
  10902. DeclContext *DC = Param->getDeclContext();
  10903. if (DC && DC->isFunctionOrMethod()) {
  10904. if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
  10905. CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
  10906. RD, /*DeclIsField*/ false);
  10907. }
  10908. }
  10909. }
  10910. return HasInvalidParm;
  10911. }
  10912. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  10913. /// or MemberExpr.
  10914. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  10915. ASTContext &Context) {
  10916. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  10917. return Context.getDeclAlign(DRE->getDecl());
  10918. if (const auto *ME = dyn_cast<MemberExpr>(E))
  10919. return Context.getDeclAlign(ME->getMemberDecl());
  10920. return TypeAlign;
  10921. }
  10922. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  10923. /// pointer cast increases the alignment requirements.
  10924. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  10925. // This is actually a lot of work to potentially be doing on every
  10926. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  10927. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  10928. return;
  10929. // Ignore dependent types.
  10930. if (T->isDependentType() || Op->getType()->isDependentType())
  10931. return;
  10932. // Require that the destination be a pointer type.
  10933. const PointerType *DestPtr = T->getAs<PointerType>();
  10934. if (!DestPtr) return;
  10935. // If the destination has alignment 1, we're done.
  10936. QualType DestPointee = DestPtr->getPointeeType();
  10937. if (DestPointee->isIncompleteType()) return;
  10938. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  10939. if (DestAlign.isOne()) return;
  10940. // Require that the source be a pointer type.
  10941. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  10942. if (!SrcPtr) return;
  10943. QualType SrcPointee = SrcPtr->getPointeeType();
  10944. // Whitelist casts from cv void*. We already implicitly
  10945. // whitelisted casts to cv void*, since they have alignment 1.
  10946. // Also whitelist casts involving incomplete types, which implicitly
  10947. // includes 'void'.
  10948. if (SrcPointee->isIncompleteType()) return;
  10949. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  10950. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  10951. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  10952. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  10953. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  10954. if (UO->getOpcode() == UO_AddrOf)
  10955. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  10956. }
  10957. if (SrcAlign >= DestAlign) return;
  10958. Diag(TRange.getBegin(), diag::warn_cast_align)
  10959. << Op->getType() << T
  10960. << static_cast<unsigned>(SrcAlign.getQuantity())
  10961. << static_cast<unsigned>(DestAlign.getQuantity())
  10962. << TRange << Op->getSourceRange();
  10963. }
  10964. /// Check whether this array fits the idiom of a size-one tail padded
  10965. /// array member of a struct.
  10966. ///
  10967. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  10968. /// commonly used to emulate flexible arrays in C89 code.
  10969. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  10970. const NamedDecl *ND) {
  10971. if (Size != 1 || !ND) return false;
  10972. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  10973. if (!FD) return false;
  10974. // Don't consider sizes resulting from macro expansions or template argument
  10975. // substitution to form C89 tail-padded arrays.
  10976. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  10977. while (TInfo) {
  10978. TypeLoc TL = TInfo->getTypeLoc();
  10979. // Look through typedefs.
  10980. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  10981. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  10982. TInfo = TDL->getTypeSourceInfo();
  10983. continue;
  10984. }
  10985. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  10986. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  10987. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  10988. return false;
  10989. }
  10990. break;
  10991. }
  10992. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  10993. if (!RD) return false;
  10994. if (RD->isUnion()) return false;
  10995. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  10996. if (!CRD->isStandardLayout()) return false;
  10997. }
  10998. // See if this is the last field decl in the record.
  10999. const Decl *D = FD;
  11000. while ((D = D->getNextDeclInContext()))
  11001. if (isa<FieldDecl>(D))
  11002. return false;
  11003. return true;
  11004. }
  11005. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  11006. const ArraySubscriptExpr *ASE,
  11007. bool AllowOnePastEnd, bool IndexNegated) {
  11008. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  11009. if (IndexExpr->isValueDependent())
  11010. return;
  11011. const Type *EffectiveType =
  11012. BaseExpr->getType()->getPointeeOrArrayElementType();
  11013. BaseExpr = BaseExpr->IgnoreParenCasts();
  11014. const ConstantArrayType *ArrayTy =
  11015. Context.getAsConstantArrayType(BaseExpr->getType());
  11016. if (!ArrayTy)
  11017. return;
  11018. const Type *BaseType = ArrayTy->getElementType().getTypePtr();
  11019. Expr::EvalResult Result;
  11020. if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
  11021. return;
  11022. llvm::APSInt index = Result.Val.getInt();
  11023. if (IndexNegated)
  11024. index = -index;
  11025. const NamedDecl *ND = nullptr;
  11026. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11027. ND = DRE->getDecl();
  11028. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11029. ND = ME->getMemberDecl();
  11030. if (index.isUnsigned() || !index.isNegative()) {
  11031. // It is possible that the type of the base expression after
  11032. // IgnoreParenCasts is incomplete, even though the type of the base
  11033. // expression before IgnoreParenCasts is complete (see PR39746 for an
  11034. // example). In this case we have no information about whether the array
  11035. // access exceeds the array bounds. However we can still diagnose an array
  11036. // access which precedes the array bounds.
  11037. if (BaseType->isIncompleteType())
  11038. return;
  11039. llvm::APInt size = ArrayTy->getSize();
  11040. if (!size.isStrictlyPositive())
  11041. return;
  11042. if (BaseType != EffectiveType) {
  11043. // Make sure we're comparing apples to apples when comparing index to size
  11044. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  11045. uint64_t array_typesize = Context.getTypeSize(BaseType);
  11046. // Handle ptrarith_typesize being zero, such as when casting to void*
  11047. if (!ptrarith_typesize) ptrarith_typesize = 1;
  11048. if (ptrarith_typesize != array_typesize) {
  11049. // There's a cast to a different size type involved
  11050. uint64_t ratio = array_typesize / ptrarith_typesize;
  11051. // TODO: Be smarter about handling cases where array_typesize is not a
  11052. // multiple of ptrarith_typesize
  11053. if (ptrarith_typesize * ratio == array_typesize)
  11054. size *= llvm::APInt(size.getBitWidth(), ratio);
  11055. }
  11056. }
  11057. if (size.getBitWidth() > index.getBitWidth())
  11058. index = index.zext(size.getBitWidth());
  11059. else if (size.getBitWidth() < index.getBitWidth())
  11060. size = size.zext(index.getBitWidth());
  11061. // For array subscripting the index must be less than size, but for pointer
  11062. // arithmetic also allow the index (offset) to be equal to size since
  11063. // computing the next address after the end of the array is legal and
  11064. // commonly done e.g. in C++ iterators and range-based for loops.
  11065. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  11066. return;
  11067. // Also don't warn for arrays of size 1 which are members of some
  11068. // structure. These are often used to approximate flexible arrays in C89
  11069. // code.
  11070. if (IsTailPaddedMemberArray(*this, size, ND))
  11071. return;
  11072. // Suppress the warning if the subscript expression (as identified by the
  11073. // ']' location) and the index expression are both from macro expansions
  11074. // within a system header.
  11075. if (ASE) {
  11076. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  11077. ASE->getRBracketLoc());
  11078. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  11079. SourceLocation IndexLoc =
  11080. SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
  11081. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  11082. return;
  11083. }
  11084. }
  11085. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  11086. if (ASE)
  11087. DiagID = diag::warn_array_index_exceeds_bounds;
  11088. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11089. PDiag(DiagID) << index.toString(10, true)
  11090. << size.toString(10, true)
  11091. << (unsigned)size.getLimitedValue(~0U)
  11092. << IndexExpr->getSourceRange());
  11093. } else {
  11094. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  11095. if (!ASE) {
  11096. DiagID = diag::warn_ptr_arith_precedes_bounds;
  11097. if (index.isNegative()) index = -index;
  11098. }
  11099. DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
  11100. PDiag(DiagID) << index.toString(10, true)
  11101. << IndexExpr->getSourceRange());
  11102. }
  11103. if (!ND) {
  11104. // Try harder to find a NamedDecl to point at in the note.
  11105. while (const ArraySubscriptExpr *ASE =
  11106. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  11107. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  11108. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  11109. ND = DRE->getDecl();
  11110. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  11111. ND = ME->getMemberDecl();
  11112. }
  11113. if (ND)
  11114. DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
  11115. PDiag(diag::note_array_index_out_of_bounds)
  11116. << ND->getDeclName());
  11117. }
  11118. void Sema::CheckArrayAccess(const Expr *expr) {
  11119. int AllowOnePastEnd = 0;
  11120. while (expr) {
  11121. expr = expr->IgnoreParenImpCasts();
  11122. switch (expr->getStmtClass()) {
  11123. case Stmt::ArraySubscriptExprClass: {
  11124. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  11125. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  11126. AllowOnePastEnd > 0);
  11127. expr = ASE->getBase();
  11128. break;
  11129. }
  11130. case Stmt::MemberExprClass: {
  11131. expr = cast<MemberExpr>(expr)->getBase();
  11132. break;
  11133. }
  11134. case Stmt::OMPArraySectionExprClass: {
  11135. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  11136. if (ASE->getLowerBound())
  11137. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  11138. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  11139. return;
  11140. }
  11141. case Stmt::UnaryOperatorClass: {
  11142. // Only unwrap the * and & unary operators
  11143. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  11144. expr = UO->getSubExpr();
  11145. switch (UO->getOpcode()) {
  11146. case UO_AddrOf:
  11147. AllowOnePastEnd++;
  11148. break;
  11149. case UO_Deref:
  11150. AllowOnePastEnd--;
  11151. break;
  11152. default:
  11153. return;
  11154. }
  11155. break;
  11156. }
  11157. case Stmt::ConditionalOperatorClass: {
  11158. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  11159. if (const Expr *lhs = cond->getLHS())
  11160. CheckArrayAccess(lhs);
  11161. if (const Expr *rhs = cond->getRHS())
  11162. CheckArrayAccess(rhs);
  11163. return;
  11164. }
  11165. case Stmt::CXXOperatorCallExprClass: {
  11166. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  11167. for (const auto *Arg : OCE->arguments())
  11168. CheckArrayAccess(Arg);
  11169. return;
  11170. }
  11171. default:
  11172. return;
  11173. }
  11174. }
  11175. }
  11176. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  11177. namespace {
  11178. struct RetainCycleOwner {
  11179. VarDecl *Variable = nullptr;
  11180. SourceRange Range;
  11181. SourceLocation Loc;
  11182. bool Indirect = false;
  11183. RetainCycleOwner() = default;
  11184. void setLocsFrom(Expr *e) {
  11185. Loc = e->getExprLoc();
  11186. Range = e->getSourceRange();
  11187. }
  11188. };
  11189. } // namespace
  11190. /// Consider whether capturing the given variable can possibly lead to
  11191. /// a retain cycle.
  11192. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  11193. // In ARC, it's captured strongly iff the variable has __strong
  11194. // lifetime. In MRR, it's captured strongly if the variable is
  11195. // __block and has an appropriate type.
  11196. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11197. return false;
  11198. owner.Variable = var;
  11199. if (ref)
  11200. owner.setLocsFrom(ref);
  11201. return true;
  11202. }
  11203. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11204. while (true) {
  11205. e = e->IgnoreParens();
  11206. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  11207. switch (cast->getCastKind()) {
  11208. case CK_BitCast:
  11209. case CK_LValueBitCast:
  11210. case CK_LValueToRValue:
  11211. case CK_ARCReclaimReturnedObject:
  11212. e = cast->getSubExpr();
  11213. continue;
  11214. default:
  11215. return false;
  11216. }
  11217. }
  11218. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  11219. ObjCIvarDecl *ivar = ref->getDecl();
  11220. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  11221. return false;
  11222. // Try to find a retain cycle in the base.
  11223. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  11224. return false;
  11225. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  11226. owner.Indirect = true;
  11227. return true;
  11228. }
  11229. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  11230. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  11231. if (!var) return false;
  11232. return considerVariable(var, ref, owner);
  11233. }
  11234. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  11235. if (member->isArrow()) return false;
  11236. // Don't count this as an indirect ownership.
  11237. e = member->getBase();
  11238. continue;
  11239. }
  11240. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  11241. // Only pay attention to pseudo-objects on property references.
  11242. ObjCPropertyRefExpr *pre
  11243. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  11244. ->IgnoreParens());
  11245. if (!pre) return false;
  11246. if (pre->isImplicitProperty()) return false;
  11247. ObjCPropertyDecl *property = pre->getExplicitProperty();
  11248. if (!property->isRetaining() &&
  11249. !(property->getPropertyIvarDecl() &&
  11250. property->getPropertyIvarDecl()->getType()
  11251. .getObjCLifetime() == Qualifiers::OCL_Strong))
  11252. return false;
  11253. owner.Indirect = true;
  11254. if (pre->isSuperReceiver()) {
  11255. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  11256. if (!owner.Variable)
  11257. return false;
  11258. owner.Loc = pre->getLocation();
  11259. owner.Range = pre->getSourceRange();
  11260. return true;
  11261. }
  11262. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  11263. ->getSourceExpr());
  11264. continue;
  11265. }
  11266. // Array ivars?
  11267. return false;
  11268. }
  11269. }
  11270. namespace {
  11271. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  11272. ASTContext &Context;
  11273. VarDecl *Variable;
  11274. Expr *Capturer = nullptr;
  11275. bool VarWillBeReased = false;
  11276. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  11277. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  11278. Context(Context), Variable(variable) {}
  11279. void VisitDeclRefExpr(DeclRefExpr *ref) {
  11280. if (ref->getDecl() == Variable && !Capturer)
  11281. Capturer = ref;
  11282. }
  11283. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  11284. if (Capturer) return;
  11285. Visit(ref->getBase());
  11286. if (Capturer && ref->isFreeIvar())
  11287. Capturer = ref;
  11288. }
  11289. void VisitBlockExpr(BlockExpr *block) {
  11290. // Look inside nested blocks
  11291. if (block->getBlockDecl()->capturesVariable(Variable))
  11292. Visit(block->getBlockDecl()->getBody());
  11293. }
  11294. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  11295. if (Capturer) return;
  11296. if (OVE->getSourceExpr())
  11297. Visit(OVE->getSourceExpr());
  11298. }
  11299. void VisitBinaryOperator(BinaryOperator *BinOp) {
  11300. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  11301. return;
  11302. Expr *LHS = BinOp->getLHS();
  11303. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  11304. if (DRE->getDecl() != Variable)
  11305. return;
  11306. if (Expr *RHS = BinOp->getRHS()) {
  11307. RHS = RHS->IgnoreParenCasts();
  11308. llvm::APSInt Value;
  11309. VarWillBeReased =
  11310. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  11311. }
  11312. }
  11313. }
  11314. };
  11315. } // namespace
  11316. /// Check whether the given argument is a block which captures a
  11317. /// variable.
  11318. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  11319. assert(owner.Variable && owner.Loc.isValid());
  11320. e = e->IgnoreParenCasts();
  11321. // Look through [^{...} copy] and Block_copy(^{...}).
  11322. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  11323. Selector Cmd = ME->getSelector();
  11324. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  11325. e = ME->getInstanceReceiver();
  11326. if (!e)
  11327. return nullptr;
  11328. e = e->IgnoreParenCasts();
  11329. }
  11330. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  11331. if (CE->getNumArgs() == 1) {
  11332. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  11333. if (Fn) {
  11334. const IdentifierInfo *FnI = Fn->getIdentifier();
  11335. if (FnI && FnI->isStr("_Block_copy")) {
  11336. e = CE->getArg(0)->IgnoreParenCasts();
  11337. }
  11338. }
  11339. }
  11340. }
  11341. BlockExpr *block = dyn_cast<BlockExpr>(e);
  11342. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  11343. return nullptr;
  11344. FindCaptureVisitor visitor(S.Context, owner.Variable);
  11345. visitor.Visit(block->getBlockDecl()->getBody());
  11346. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  11347. }
  11348. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  11349. RetainCycleOwner &owner) {
  11350. assert(capturer);
  11351. assert(owner.Variable && owner.Loc.isValid());
  11352. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  11353. << owner.Variable << capturer->getSourceRange();
  11354. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  11355. << owner.Indirect << owner.Range;
  11356. }
  11357. /// Check for a keyword selector that starts with the word 'add' or
  11358. /// 'set'.
  11359. static bool isSetterLikeSelector(Selector sel) {
  11360. if (sel.isUnarySelector()) return false;
  11361. StringRef str = sel.getNameForSlot(0);
  11362. while (!str.empty() && str.front() == '_') str = str.substr(1);
  11363. if (str.startswith("set"))
  11364. str = str.substr(3);
  11365. else if (str.startswith("add")) {
  11366. // Specially whitelist 'addOperationWithBlock:'.
  11367. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  11368. return false;
  11369. str = str.substr(3);
  11370. }
  11371. else
  11372. return false;
  11373. if (str.empty()) return true;
  11374. return !isLowercase(str.front());
  11375. }
  11376. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  11377. ObjCMessageExpr *Message) {
  11378. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  11379. Message->getReceiverInterface(),
  11380. NSAPI::ClassId_NSMutableArray);
  11381. if (!IsMutableArray) {
  11382. return None;
  11383. }
  11384. Selector Sel = Message->getSelector();
  11385. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  11386. S.NSAPIObj->getNSArrayMethodKind(Sel);
  11387. if (!MKOpt) {
  11388. return None;
  11389. }
  11390. NSAPI::NSArrayMethodKind MK = *MKOpt;
  11391. switch (MK) {
  11392. case NSAPI::NSMutableArr_addObject:
  11393. case NSAPI::NSMutableArr_insertObjectAtIndex:
  11394. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  11395. return 0;
  11396. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  11397. return 1;
  11398. default:
  11399. return None;
  11400. }
  11401. return None;
  11402. }
  11403. static
  11404. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  11405. ObjCMessageExpr *Message) {
  11406. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  11407. Message->getReceiverInterface(),
  11408. NSAPI::ClassId_NSMutableDictionary);
  11409. if (!IsMutableDictionary) {
  11410. return None;
  11411. }
  11412. Selector Sel = Message->getSelector();
  11413. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  11414. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  11415. if (!MKOpt) {
  11416. return None;
  11417. }
  11418. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  11419. switch (MK) {
  11420. case NSAPI::NSMutableDict_setObjectForKey:
  11421. case NSAPI::NSMutableDict_setValueForKey:
  11422. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  11423. return 0;
  11424. default:
  11425. return None;
  11426. }
  11427. return None;
  11428. }
  11429. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  11430. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  11431. Message->getReceiverInterface(),
  11432. NSAPI::ClassId_NSMutableSet);
  11433. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  11434. Message->getReceiverInterface(),
  11435. NSAPI::ClassId_NSMutableOrderedSet);
  11436. if (!IsMutableSet && !IsMutableOrderedSet) {
  11437. return None;
  11438. }
  11439. Selector Sel = Message->getSelector();
  11440. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  11441. if (!MKOpt) {
  11442. return None;
  11443. }
  11444. NSAPI::NSSetMethodKind MK = *MKOpt;
  11445. switch (MK) {
  11446. case NSAPI::NSMutableSet_addObject:
  11447. case NSAPI::NSOrderedSet_setObjectAtIndex:
  11448. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  11449. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  11450. return 0;
  11451. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  11452. return 1;
  11453. }
  11454. return None;
  11455. }
  11456. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  11457. if (!Message->isInstanceMessage()) {
  11458. return;
  11459. }
  11460. Optional<int> ArgOpt;
  11461. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  11462. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  11463. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  11464. return;
  11465. }
  11466. int ArgIndex = *ArgOpt;
  11467. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  11468. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  11469. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  11470. }
  11471. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  11472. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11473. if (ArgRE->isObjCSelfExpr()) {
  11474. Diag(Message->getSourceRange().getBegin(),
  11475. diag::warn_objc_circular_container)
  11476. << ArgRE->getDecl() << StringRef("'super'");
  11477. }
  11478. }
  11479. } else {
  11480. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  11481. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  11482. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  11483. }
  11484. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  11485. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  11486. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  11487. ValueDecl *Decl = ReceiverRE->getDecl();
  11488. Diag(Message->getSourceRange().getBegin(),
  11489. diag::warn_objc_circular_container)
  11490. << Decl << Decl;
  11491. if (!ArgRE->isObjCSelfExpr()) {
  11492. Diag(Decl->getLocation(),
  11493. diag::note_objc_circular_container_declared_here)
  11494. << Decl;
  11495. }
  11496. }
  11497. }
  11498. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  11499. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  11500. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  11501. ObjCIvarDecl *Decl = IvarRE->getDecl();
  11502. Diag(Message->getSourceRange().getBegin(),
  11503. diag::warn_objc_circular_container)
  11504. << Decl << Decl;
  11505. Diag(Decl->getLocation(),
  11506. diag::note_objc_circular_container_declared_here)
  11507. << Decl;
  11508. }
  11509. }
  11510. }
  11511. }
  11512. }
  11513. /// Check a message send to see if it's likely to cause a retain cycle.
  11514. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  11515. // Only check instance methods whose selector looks like a setter.
  11516. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  11517. return;
  11518. // Try to find a variable that the receiver is strongly owned by.
  11519. RetainCycleOwner owner;
  11520. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  11521. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  11522. return;
  11523. } else {
  11524. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  11525. owner.Variable = getCurMethodDecl()->getSelfDecl();
  11526. owner.Loc = msg->getSuperLoc();
  11527. owner.Range = msg->getSuperLoc();
  11528. }
  11529. // Check whether the receiver is captured by any of the arguments.
  11530. const ObjCMethodDecl *MD = msg->getMethodDecl();
  11531. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  11532. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  11533. // noescape blocks should not be retained by the method.
  11534. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  11535. continue;
  11536. return diagnoseRetainCycle(*this, capturer, owner);
  11537. }
  11538. }
  11539. }
  11540. /// Check a property assign to see if it's likely to cause a retain cycle.
  11541. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  11542. RetainCycleOwner owner;
  11543. if (!findRetainCycleOwner(*this, receiver, owner))
  11544. return;
  11545. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  11546. diagnoseRetainCycle(*this, capturer, owner);
  11547. }
  11548. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  11549. RetainCycleOwner Owner;
  11550. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  11551. return;
  11552. // Because we don't have an expression for the variable, we have to set the
  11553. // location explicitly here.
  11554. Owner.Loc = Var->getLocation();
  11555. Owner.Range = Var->getSourceRange();
  11556. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  11557. diagnoseRetainCycle(*this, Capturer, Owner);
  11558. }
  11559. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  11560. Expr *RHS, bool isProperty) {
  11561. // Check if RHS is an Objective-C object literal, which also can get
  11562. // immediately zapped in a weak reference. Note that we explicitly
  11563. // allow ObjCStringLiterals, since those are designed to never really die.
  11564. RHS = RHS->IgnoreParenImpCasts();
  11565. // This enum needs to match with the 'select' in
  11566. // warn_objc_arc_literal_assign (off-by-1).
  11567. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  11568. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  11569. return false;
  11570. S.Diag(Loc, diag::warn_arc_literal_assign)
  11571. << (unsigned) Kind
  11572. << (isProperty ? 0 : 1)
  11573. << RHS->getSourceRange();
  11574. return true;
  11575. }
  11576. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  11577. Qualifiers::ObjCLifetime LT,
  11578. Expr *RHS, bool isProperty) {
  11579. // Strip off any implicit cast added to get to the one ARC-specific.
  11580. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11581. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11582. S.Diag(Loc, diag::warn_arc_retained_assign)
  11583. << (LT == Qualifiers::OCL_ExplicitNone)
  11584. << (isProperty ? 0 : 1)
  11585. << RHS->getSourceRange();
  11586. return true;
  11587. }
  11588. RHS = cast->getSubExpr();
  11589. }
  11590. if (LT == Qualifiers::OCL_Weak &&
  11591. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  11592. return true;
  11593. return false;
  11594. }
  11595. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  11596. QualType LHS, Expr *RHS) {
  11597. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  11598. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  11599. return false;
  11600. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  11601. return true;
  11602. return false;
  11603. }
  11604. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  11605. Expr *LHS, Expr *RHS) {
  11606. QualType LHSType;
  11607. // PropertyRef on LHS type need be directly obtained from
  11608. // its declaration as it has a PseudoType.
  11609. ObjCPropertyRefExpr *PRE
  11610. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  11611. if (PRE && !PRE->isImplicitProperty()) {
  11612. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11613. if (PD)
  11614. LHSType = PD->getType();
  11615. }
  11616. if (LHSType.isNull())
  11617. LHSType = LHS->getType();
  11618. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  11619. if (LT == Qualifiers::OCL_Weak) {
  11620. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  11621. getCurFunction()->markSafeWeakUse(LHS);
  11622. }
  11623. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  11624. return;
  11625. // FIXME. Check for other life times.
  11626. if (LT != Qualifiers::OCL_None)
  11627. return;
  11628. if (PRE) {
  11629. if (PRE->isImplicitProperty())
  11630. return;
  11631. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  11632. if (!PD)
  11633. return;
  11634. unsigned Attributes = PD->getPropertyAttributes();
  11635. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  11636. // when 'assign' attribute was not explicitly specified
  11637. // by user, ignore it and rely on property type itself
  11638. // for lifetime info.
  11639. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  11640. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  11641. LHSType->isObjCRetainableType())
  11642. return;
  11643. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  11644. if (cast->getCastKind() == CK_ARCConsumeObject) {
  11645. Diag(Loc, diag::warn_arc_retained_property_assign)
  11646. << RHS->getSourceRange();
  11647. return;
  11648. }
  11649. RHS = cast->getSubExpr();
  11650. }
  11651. }
  11652. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  11653. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  11654. return;
  11655. }
  11656. }
  11657. }
  11658. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  11659. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  11660. SourceLocation StmtLoc,
  11661. const NullStmt *Body) {
  11662. // Do not warn if the body is a macro that expands to nothing, e.g:
  11663. //
  11664. // #define CALL(x)
  11665. // if (condition)
  11666. // CALL(0);
  11667. if (Body->hasLeadingEmptyMacro())
  11668. return false;
  11669. // Get line numbers of statement and body.
  11670. bool StmtLineInvalid;
  11671. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  11672. &StmtLineInvalid);
  11673. if (StmtLineInvalid)
  11674. return false;
  11675. bool BodyLineInvalid;
  11676. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  11677. &BodyLineInvalid);
  11678. if (BodyLineInvalid)
  11679. return false;
  11680. // Warn if null statement and body are on the same line.
  11681. if (StmtLine != BodyLine)
  11682. return false;
  11683. return true;
  11684. }
  11685. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  11686. const Stmt *Body,
  11687. unsigned DiagID) {
  11688. // Since this is a syntactic check, don't emit diagnostic for template
  11689. // instantiations, this just adds noise.
  11690. if (CurrentInstantiationScope)
  11691. return;
  11692. // The body should be a null statement.
  11693. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11694. if (!NBody)
  11695. return;
  11696. // Do the usual checks.
  11697. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11698. return;
  11699. Diag(NBody->getSemiLoc(), DiagID);
  11700. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11701. }
  11702. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  11703. const Stmt *PossibleBody) {
  11704. assert(!CurrentInstantiationScope); // Ensured by caller
  11705. SourceLocation StmtLoc;
  11706. const Stmt *Body;
  11707. unsigned DiagID;
  11708. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  11709. StmtLoc = FS->getRParenLoc();
  11710. Body = FS->getBody();
  11711. DiagID = diag::warn_empty_for_body;
  11712. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  11713. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  11714. Body = WS->getBody();
  11715. DiagID = diag::warn_empty_while_body;
  11716. } else
  11717. return; // Neither `for' nor `while'.
  11718. // The body should be a null statement.
  11719. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  11720. if (!NBody)
  11721. return;
  11722. // Skip expensive checks if diagnostic is disabled.
  11723. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  11724. return;
  11725. // Do the usual checks.
  11726. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  11727. return;
  11728. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  11729. // noise level low, emit diagnostics only if for/while is followed by a
  11730. // CompoundStmt, e.g.:
  11731. // for (int i = 0; i < n; i++);
  11732. // {
  11733. // a(i);
  11734. // }
  11735. // or if for/while is followed by a statement with more indentation
  11736. // than for/while itself:
  11737. // for (int i = 0; i < n; i++);
  11738. // a(i);
  11739. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  11740. if (!ProbableTypo) {
  11741. bool BodyColInvalid;
  11742. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  11743. PossibleBody->getBeginLoc(), &BodyColInvalid);
  11744. if (BodyColInvalid)
  11745. return;
  11746. bool StmtColInvalid;
  11747. unsigned StmtCol =
  11748. SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
  11749. if (StmtColInvalid)
  11750. return;
  11751. if (BodyCol > StmtCol)
  11752. ProbableTypo = true;
  11753. }
  11754. if (ProbableTypo) {
  11755. Diag(NBody->getSemiLoc(), DiagID);
  11756. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  11757. }
  11758. }
  11759. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  11760. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  11761. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  11762. SourceLocation OpLoc) {
  11763. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  11764. return;
  11765. if (inTemplateInstantiation())
  11766. return;
  11767. // Strip parens and casts away.
  11768. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11769. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11770. // Check for a call expression
  11771. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  11772. if (!CE || CE->getNumArgs() != 1)
  11773. return;
  11774. // Check for a call to std::move
  11775. if (!CE->isCallToStdMove())
  11776. return;
  11777. // Get argument from std::move
  11778. RHSExpr = CE->getArg(0);
  11779. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11780. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11781. // Two DeclRefExpr's, check that the decls are the same.
  11782. if (LHSDeclRef && RHSDeclRef) {
  11783. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11784. return;
  11785. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11786. RHSDeclRef->getDecl()->getCanonicalDecl())
  11787. return;
  11788. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11789. << LHSExpr->getSourceRange()
  11790. << RHSExpr->getSourceRange();
  11791. return;
  11792. }
  11793. // Member variables require a different approach to check for self moves.
  11794. // MemberExpr's are the same if every nested MemberExpr refers to the same
  11795. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  11796. // the base Expr's are CXXThisExpr's.
  11797. const Expr *LHSBase = LHSExpr;
  11798. const Expr *RHSBase = RHSExpr;
  11799. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  11800. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  11801. if (!LHSME || !RHSME)
  11802. return;
  11803. while (LHSME && RHSME) {
  11804. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  11805. RHSME->getMemberDecl()->getCanonicalDecl())
  11806. return;
  11807. LHSBase = LHSME->getBase();
  11808. RHSBase = RHSME->getBase();
  11809. LHSME = dyn_cast<MemberExpr>(LHSBase);
  11810. RHSME = dyn_cast<MemberExpr>(RHSBase);
  11811. }
  11812. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  11813. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  11814. if (LHSDeclRef && RHSDeclRef) {
  11815. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  11816. return;
  11817. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  11818. RHSDeclRef->getDecl()->getCanonicalDecl())
  11819. return;
  11820. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11821. << LHSExpr->getSourceRange()
  11822. << RHSExpr->getSourceRange();
  11823. return;
  11824. }
  11825. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  11826. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  11827. << LHSExpr->getSourceRange()
  11828. << RHSExpr->getSourceRange();
  11829. }
  11830. //===--- Layout compatibility ----------------------------------------------//
  11831. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  11832. /// Check if two enumeration types are layout-compatible.
  11833. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  11834. // C++11 [dcl.enum] p8:
  11835. // Two enumeration types are layout-compatible if they have the same
  11836. // underlying type.
  11837. return ED1->isComplete() && ED2->isComplete() &&
  11838. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  11839. }
  11840. /// Check if two fields are layout-compatible.
  11841. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  11842. FieldDecl *Field2) {
  11843. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  11844. return false;
  11845. if (Field1->isBitField() != Field2->isBitField())
  11846. return false;
  11847. if (Field1->isBitField()) {
  11848. // Make sure that the bit-fields are the same length.
  11849. unsigned Bits1 = Field1->getBitWidthValue(C);
  11850. unsigned Bits2 = Field2->getBitWidthValue(C);
  11851. if (Bits1 != Bits2)
  11852. return false;
  11853. }
  11854. return true;
  11855. }
  11856. /// Check if two standard-layout structs are layout-compatible.
  11857. /// (C++11 [class.mem] p17)
  11858. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  11859. RecordDecl *RD2) {
  11860. // If both records are C++ classes, check that base classes match.
  11861. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  11862. // If one of records is a CXXRecordDecl we are in C++ mode,
  11863. // thus the other one is a CXXRecordDecl, too.
  11864. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  11865. // Check number of base classes.
  11866. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  11867. return false;
  11868. // Check the base classes.
  11869. for (CXXRecordDecl::base_class_const_iterator
  11870. Base1 = D1CXX->bases_begin(),
  11871. BaseEnd1 = D1CXX->bases_end(),
  11872. Base2 = D2CXX->bases_begin();
  11873. Base1 != BaseEnd1;
  11874. ++Base1, ++Base2) {
  11875. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  11876. return false;
  11877. }
  11878. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  11879. // If only RD2 is a C++ class, it should have zero base classes.
  11880. if (D2CXX->getNumBases() > 0)
  11881. return false;
  11882. }
  11883. // Check the fields.
  11884. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  11885. Field2End = RD2->field_end(),
  11886. Field1 = RD1->field_begin(),
  11887. Field1End = RD1->field_end();
  11888. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  11889. if (!isLayoutCompatible(C, *Field1, *Field2))
  11890. return false;
  11891. }
  11892. if (Field1 != Field1End || Field2 != Field2End)
  11893. return false;
  11894. return true;
  11895. }
  11896. /// Check if two standard-layout unions are layout-compatible.
  11897. /// (C++11 [class.mem] p18)
  11898. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  11899. RecordDecl *RD2) {
  11900. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  11901. for (auto *Field2 : RD2->fields())
  11902. UnmatchedFields.insert(Field2);
  11903. for (auto *Field1 : RD1->fields()) {
  11904. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  11905. I = UnmatchedFields.begin(),
  11906. E = UnmatchedFields.end();
  11907. for ( ; I != E; ++I) {
  11908. if (isLayoutCompatible(C, Field1, *I)) {
  11909. bool Result = UnmatchedFields.erase(*I);
  11910. (void) Result;
  11911. assert(Result);
  11912. break;
  11913. }
  11914. }
  11915. if (I == E)
  11916. return false;
  11917. }
  11918. return UnmatchedFields.empty();
  11919. }
  11920. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  11921. RecordDecl *RD2) {
  11922. if (RD1->isUnion() != RD2->isUnion())
  11923. return false;
  11924. if (RD1->isUnion())
  11925. return isLayoutCompatibleUnion(C, RD1, RD2);
  11926. else
  11927. return isLayoutCompatibleStruct(C, RD1, RD2);
  11928. }
  11929. /// Check if two types are layout-compatible in C++11 sense.
  11930. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  11931. if (T1.isNull() || T2.isNull())
  11932. return false;
  11933. // C++11 [basic.types] p11:
  11934. // If two types T1 and T2 are the same type, then T1 and T2 are
  11935. // layout-compatible types.
  11936. if (C.hasSameType(T1, T2))
  11937. return true;
  11938. T1 = T1.getCanonicalType().getUnqualifiedType();
  11939. T2 = T2.getCanonicalType().getUnqualifiedType();
  11940. const Type::TypeClass TC1 = T1->getTypeClass();
  11941. const Type::TypeClass TC2 = T2->getTypeClass();
  11942. if (TC1 != TC2)
  11943. return false;
  11944. if (TC1 == Type::Enum) {
  11945. return isLayoutCompatible(C,
  11946. cast<EnumType>(T1)->getDecl(),
  11947. cast<EnumType>(T2)->getDecl());
  11948. } else if (TC1 == Type::Record) {
  11949. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  11950. return false;
  11951. return isLayoutCompatible(C,
  11952. cast<RecordType>(T1)->getDecl(),
  11953. cast<RecordType>(T2)->getDecl());
  11954. }
  11955. return false;
  11956. }
  11957. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  11958. /// Given a type tag expression find the type tag itself.
  11959. ///
  11960. /// \param TypeExpr Type tag expression, as it appears in user's code.
  11961. ///
  11962. /// \param VD Declaration of an identifier that appears in a type tag.
  11963. ///
  11964. /// \param MagicValue Type tag magic value.
  11965. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  11966. const ValueDecl **VD, uint64_t *MagicValue) {
  11967. while(true) {
  11968. if (!TypeExpr)
  11969. return false;
  11970. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  11971. switch (TypeExpr->getStmtClass()) {
  11972. case Stmt::UnaryOperatorClass: {
  11973. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  11974. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  11975. TypeExpr = UO->getSubExpr();
  11976. continue;
  11977. }
  11978. return false;
  11979. }
  11980. case Stmt::DeclRefExprClass: {
  11981. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  11982. *VD = DRE->getDecl();
  11983. return true;
  11984. }
  11985. case Stmt::IntegerLiteralClass: {
  11986. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  11987. llvm::APInt MagicValueAPInt = IL->getValue();
  11988. if (MagicValueAPInt.getActiveBits() <= 64) {
  11989. *MagicValue = MagicValueAPInt.getZExtValue();
  11990. return true;
  11991. } else
  11992. return false;
  11993. }
  11994. case Stmt::BinaryConditionalOperatorClass:
  11995. case Stmt::ConditionalOperatorClass: {
  11996. const AbstractConditionalOperator *ACO =
  11997. cast<AbstractConditionalOperator>(TypeExpr);
  11998. bool Result;
  11999. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  12000. if (Result)
  12001. TypeExpr = ACO->getTrueExpr();
  12002. else
  12003. TypeExpr = ACO->getFalseExpr();
  12004. continue;
  12005. }
  12006. return false;
  12007. }
  12008. case Stmt::BinaryOperatorClass: {
  12009. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  12010. if (BO->getOpcode() == BO_Comma) {
  12011. TypeExpr = BO->getRHS();
  12012. continue;
  12013. }
  12014. return false;
  12015. }
  12016. default:
  12017. return false;
  12018. }
  12019. }
  12020. }
  12021. /// Retrieve the C type corresponding to type tag TypeExpr.
  12022. ///
  12023. /// \param TypeExpr Expression that specifies a type tag.
  12024. ///
  12025. /// \param MagicValues Registered magic values.
  12026. ///
  12027. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  12028. /// kind.
  12029. ///
  12030. /// \param TypeInfo Information about the corresponding C type.
  12031. ///
  12032. /// \returns true if the corresponding C type was found.
  12033. static bool GetMatchingCType(
  12034. const IdentifierInfo *ArgumentKind,
  12035. const Expr *TypeExpr, const ASTContext &Ctx,
  12036. const llvm::DenseMap<Sema::TypeTagMagicValue,
  12037. Sema::TypeTagData> *MagicValues,
  12038. bool &FoundWrongKind,
  12039. Sema::TypeTagData &TypeInfo) {
  12040. FoundWrongKind = false;
  12041. // Variable declaration that has type_tag_for_datatype attribute.
  12042. const ValueDecl *VD = nullptr;
  12043. uint64_t MagicValue;
  12044. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  12045. return false;
  12046. if (VD) {
  12047. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  12048. if (I->getArgumentKind() != ArgumentKind) {
  12049. FoundWrongKind = true;
  12050. return false;
  12051. }
  12052. TypeInfo.Type = I->getMatchingCType();
  12053. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  12054. TypeInfo.MustBeNull = I->getMustBeNull();
  12055. return true;
  12056. }
  12057. return false;
  12058. }
  12059. if (!MagicValues)
  12060. return false;
  12061. llvm::DenseMap<Sema::TypeTagMagicValue,
  12062. Sema::TypeTagData>::const_iterator I =
  12063. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  12064. if (I == MagicValues->end())
  12065. return false;
  12066. TypeInfo = I->second;
  12067. return true;
  12068. }
  12069. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  12070. uint64_t MagicValue, QualType Type,
  12071. bool LayoutCompatible,
  12072. bool MustBeNull) {
  12073. if (!TypeTagForDatatypeMagicValues)
  12074. TypeTagForDatatypeMagicValues.reset(
  12075. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  12076. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  12077. (*TypeTagForDatatypeMagicValues)[Magic] =
  12078. TypeTagData(Type, LayoutCompatible, MustBeNull);
  12079. }
  12080. static bool IsSameCharType(QualType T1, QualType T2) {
  12081. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  12082. if (!BT1)
  12083. return false;
  12084. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  12085. if (!BT2)
  12086. return false;
  12087. BuiltinType::Kind T1Kind = BT1->getKind();
  12088. BuiltinType::Kind T2Kind = BT2->getKind();
  12089. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  12090. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  12091. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  12092. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  12093. }
  12094. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  12095. const ArrayRef<const Expr *> ExprArgs,
  12096. SourceLocation CallSiteLoc) {
  12097. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  12098. bool IsPointerAttr = Attr->getIsPointer();
  12099. // Retrieve the argument representing the 'type_tag'.
  12100. unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
  12101. if (TypeTagIdxAST >= ExprArgs.size()) {
  12102. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12103. << 0 << Attr->getTypeTagIdx().getSourceIndex();
  12104. return;
  12105. }
  12106. const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
  12107. bool FoundWrongKind;
  12108. TypeTagData TypeInfo;
  12109. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  12110. TypeTagForDatatypeMagicValues.get(),
  12111. FoundWrongKind, TypeInfo)) {
  12112. if (FoundWrongKind)
  12113. Diag(TypeTagExpr->getExprLoc(),
  12114. diag::warn_type_tag_for_datatype_wrong_kind)
  12115. << TypeTagExpr->getSourceRange();
  12116. return;
  12117. }
  12118. // Retrieve the argument representing the 'arg_idx'.
  12119. unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
  12120. if (ArgumentIdxAST >= ExprArgs.size()) {
  12121. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  12122. << 1 << Attr->getArgumentIdx().getSourceIndex();
  12123. return;
  12124. }
  12125. const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
  12126. if (IsPointerAttr) {
  12127. // Skip implicit cast of pointer to `void *' (as a function argument).
  12128. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  12129. if (ICE->getType()->isVoidPointerType() &&
  12130. ICE->getCastKind() == CK_BitCast)
  12131. ArgumentExpr = ICE->getSubExpr();
  12132. }
  12133. QualType ArgumentType = ArgumentExpr->getType();
  12134. // Passing a `void*' pointer shouldn't trigger a warning.
  12135. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  12136. return;
  12137. if (TypeInfo.MustBeNull) {
  12138. // Type tag with matching void type requires a null pointer.
  12139. if (!ArgumentExpr->isNullPointerConstant(Context,
  12140. Expr::NPC_ValueDependentIsNotNull)) {
  12141. Diag(ArgumentExpr->getExprLoc(),
  12142. diag::warn_type_safety_null_pointer_required)
  12143. << ArgumentKind->getName()
  12144. << ArgumentExpr->getSourceRange()
  12145. << TypeTagExpr->getSourceRange();
  12146. }
  12147. return;
  12148. }
  12149. QualType RequiredType = TypeInfo.Type;
  12150. if (IsPointerAttr)
  12151. RequiredType = Context.getPointerType(RequiredType);
  12152. bool mismatch = false;
  12153. if (!TypeInfo.LayoutCompatible) {
  12154. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  12155. // C++11 [basic.fundamental] p1:
  12156. // Plain char, signed char, and unsigned char are three distinct types.
  12157. //
  12158. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  12159. // char' depending on the current char signedness mode.
  12160. if (mismatch)
  12161. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  12162. RequiredType->getPointeeType())) ||
  12163. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  12164. mismatch = false;
  12165. } else
  12166. if (IsPointerAttr)
  12167. mismatch = !isLayoutCompatible(Context,
  12168. ArgumentType->getPointeeType(),
  12169. RequiredType->getPointeeType());
  12170. else
  12171. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  12172. if (mismatch)
  12173. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  12174. << ArgumentType << ArgumentKind
  12175. << TypeInfo.LayoutCompatible << RequiredType
  12176. << ArgumentExpr->getSourceRange()
  12177. << TypeTagExpr->getSourceRange();
  12178. }
  12179. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  12180. CharUnits Alignment) {
  12181. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  12182. }
  12183. void Sema::DiagnoseMisalignedMembers() {
  12184. for (MisalignedMember &m : MisalignedMembers) {
  12185. const NamedDecl *ND = m.RD;
  12186. if (ND->getName().empty()) {
  12187. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  12188. ND = TD;
  12189. }
  12190. Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
  12191. << m.MD << ND << m.E->getSourceRange();
  12192. }
  12193. MisalignedMembers.clear();
  12194. }
  12195. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  12196. E = E->IgnoreParens();
  12197. if (!T->isPointerType() && !T->isIntegerType())
  12198. return;
  12199. if (isa<UnaryOperator>(E) &&
  12200. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  12201. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  12202. if (isa<MemberExpr>(Op)) {
  12203. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  12204. MisalignedMember(Op));
  12205. if (MA != MisalignedMembers.end() &&
  12206. (T->isIntegerType() ||
  12207. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  12208. Context.getTypeAlignInChars(
  12209. T->getPointeeType()) <= MA->Alignment))))
  12210. MisalignedMembers.erase(MA);
  12211. }
  12212. }
  12213. }
  12214. void Sema::RefersToMemberWithReducedAlignment(
  12215. Expr *E,
  12216. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  12217. Action) {
  12218. const auto *ME = dyn_cast<MemberExpr>(E);
  12219. if (!ME)
  12220. return;
  12221. // No need to check expressions with an __unaligned-qualified type.
  12222. if (E->getType().getQualifiers().hasUnaligned())
  12223. return;
  12224. // For a chain of MemberExpr like "a.b.c.d" this list
  12225. // will keep FieldDecl's like [d, c, b].
  12226. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  12227. const MemberExpr *TopME = nullptr;
  12228. bool AnyIsPacked = false;
  12229. do {
  12230. QualType BaseType = ME->getBase()->getType();
  12231. if (ME->isArrow())
  12232. BaseType = BaseType->getPointeeType();
  12233. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  12234. if (RD->isInvalidDecl())
  12235. return;
  12236. ValueDecl *MD = ME->getMemberDecl();
  12237. auto *FD = dyn_cast<FieldDecl>(MD);
  12238. // We do not care about non-data members.
  12239. if (!FD || FD->isInvalidDecl())
  12240. return;
  12241. AnyIsPacked =
  12242. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  12243. ReverseMemberChain.push_back(FD);
  12244. TopME = ME;
  12245. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  12246. } while (ME);
  12247. assert(TopME && "We did not compute a topmost MemberExpr!");
  12248. // Not the scope of this diagnostic.
  12249. if (!AnyIsPacked)
  12250. return;
  12251. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  12252. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  12253. // TODO: The innermost base of the member expression may be too complicated.
  12254. // For now, just disregard these cases. This is left for future
  12255. // improvement.
  12256. if (!DRE && !isa<CXXThisExpr>(TopBase))
  12257. return;
  12258. // Alignment expected by the whole expression.
  12259. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  12260. // No need to do anything else with this case.
  12261. if (ExpectedAlignment.isOne())
  12262. return;
  12263. // Synthesize offset of the whole access.
  12264. CharUnits Offset;
  12265. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  12266. I++) {
  12267. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  12268. }
  12269. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  12270. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  12271. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  12272. // The base expression of the innermost MemberExpr may give
  12273. // stronger guarantees than the class containing the member.
  12274. if (DRE && !TopME->isArrow()) {
  12275. const ValueDecl *VD = DRE->getDecl();
  12276. if (!VD->getType()->isReferenceType())
  12277. CompleteObjectAlignment =
  12278. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  12279. }
  12280. // Check if the synthesized offset fulfills the alignment.
  12281. if (Offset % ExpectedAlignment != 0 ||
  12282. // It may fulfill the offset it but the effective alignment may still be
  12283. // lower than the expected expression alignment.
  12284. CompleteObjectAlignment < ExpectedAlignment) {
  12285. // If this happens, we want to determine a sensible culprit of this.
  12286. // Intuitively, watching the chain of member expressions from right to
  12287. // left, we start with the required alignment (as required by the field
  12288. // type) but some packed attribute in that chain has reduced the alignment.
  12289. // It may happen that another packed structure increases it again. But if
  12290. // we are here such increase has not been enough. So pointing the first
  12291. // FieldDecl that either is packed or else its RecordDecl is,
  12292. // seems reasonable.
  12293. FieldDecl *FD = nullptr;
  12294. CharUnits Alignment;
  12295. for (FieldDecl *FDI : ReverseMemberChain) {
  12296. if (FDI->hasAttr<PackedAttr>() ||
  12297. FDI->getParent()->hasAttr<PackedAttr>()) {
  12298. FD = FDI;
  12299. Alignment = std::min(
  12300. Context.getTypeAlignInChars(FD->getType()),
  12301. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  12302. break;
  12303. }
  12304. }
  12305. assert(FD && "We did not find a packed FieldDecl!");
  12306. Action(E, FD->getParent(), FD, Alignment);
  12307. }
  12308. }
  12309. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  12310. using namespace std::placeholders;
  12311. RefersToMemberWithReducedAlignment(
  12312. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  12313. _2, _3, _4));
  12314. }