CGExprScalar.cpp 204 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187
  1. //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
  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 contains code to emit Expr nodes with scalar LLVM types as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCleanup.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CGOpenMPRuntime.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "ConstantEmitter.h"
  20. #include "TargetInfo.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/Attr.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/AST/RecordLayout.h"
  26. #include "clang/AST/StmtVisitor.h"
  27. #include "clang/Basic/CodeGenOptions.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "llvm/ADT/APFixedPoint.h"
  30. #include "llvm/ADT/Optional.h"
  31. #include "llvm/IR/CFG.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/FixedPointBuilder.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GetElementPtrTypeIterator.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/IntrinsicsPowerPC.h"
  40. #include "llvm/IR/MatrixBuilder.h"
  41. #include "llvm/IR/Module.h"
  42. #include <cstdarg>
  43. using namespace clang;
  44. using namespace CodeGen;
  45. using llvm::Value;
  46. //===----------------------------------------------------------------------===//
  47. // Scalar Expression Emitter
  48. //===----------------------------------------------------------------------===//
  49. namespace {
  50. /// Determine whether the given binary operation may overflow.
  51. /// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
  52. /// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
  53. /// the returned overflow check is precise. The returned value is 'true' for
  54. /// all other opcodes, to be conservative.
  55. bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
  56. BinaryOperator::Opcode Opcode, bool Signed,
  57. llvm::APInt &Result) {
  58. // Assume overflow is possible, unless we can prove otherwise.
  59. bool Overflow = true;
  60. const auto &LHSAP = LHS->getValue();
  61. const auto &RHSAP = RHS->getValue();
  62. if (Opcode == BO_Add) {
  63. if (Signed)
  64. Result = LHSAP.sadd_ov(RHSAP, Overflow);
  65. else
  66. Result = LHSAP.uadd_ov(RHSAP, Overflow);
  67. } else if (Opcode == BO_Sub) {
  68. if (Signed)
  69. Result = LHSAP.ssub_ov(RHSAP, Overflow);
  70. else
  71. Result = LHSAP.usub_ov(RHSAP, Overflow);
  72. } else if (Opcode == BO_Mul) {
  73. if (Signed)
  74. Result = LHSAP.smul_ov(RHSAP, Overflow);
  75. else
  76. Result = LHSAP.umul_ov(RHSAP, Overflow);
  77. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  78. if (Signed && !RHS->isZero())
  79. Result = LHSAP.sdiv_ov(RHSAP, Overflow);
  80. else
  81. return false;
  82. }
  83. return Overflow;
  84. }
  85. struct BinOpInfo {
  86. Value *LHS;
  87. Value *RHS;
  88. QualType Ty; // Computation Type.
  89. BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
  90. FPOptions FPFeatures;
  91. const Expr *E; // Entire expr, for error unsupported. May not be binop.
  92. /// Check if the binop can result in integer overflow.
  93. bool mayHaveIntegerOverflow() const {
  94. // Without constant input, we can't rule out overflow.
  95. auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
  96. auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
  97. if (!LHSCI || !RHSCI)
  98. return true;
  99. llvm::APInt Result;
  100. return ::mayHaveIntegerOverflow(
  101. LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
  102. }
  103. /// Check if the binop computes a division or a remainder.
  104. bool isDivremOp() const {
  105. return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
  106. Opcode == BO_RemAssign;
  107. }
  108. /// Check if the binop can result in an integer division by zero.
  109. bool mayHaveIntegerDivisionByZero() const {
  110. if (isDivremOp())
  111. if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
  112. return CI->isZero();
  113. return true;
  114. }
  115. /// Check if the binop can result in a float division by zero.
  116. bool mayHaveFloatDivisionByZero() const {
  117. if (isDivremOp())
  118. if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
  119. return CFP->isZero();
  120. return true;
  121. }
  122. /// Check if at least one operand is a fixed point type. In such cases, this
  123. /// operation did not follow usual arithmetic conversion and both operands
  124. /// might not be of the same type.
  125. bool isFixedPointOp() const {
  126. // We cannot simply check the result type since comparison operations return
  127. // an int.
  128. if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
  129. QualType LHSType = BinOp->getLHS()->getType();
  130. QualType RHSType = BinOp->getRHS()->getType();
  131. return LHSType->isFixedPointType() || RHSType->isFixedPointType();
  132. }
  133. if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
  134. return UnOp->getSubExpr()->getType()->isFixedPointType();
  135. return false;
  136. }
  137. };
  138. static bool MustVisitNullValue(const Expr *E) {
  139. // If a null pointer expression's type is the C++0x nullptr_t, then
  140. // it's not necessarily a simple constant and it must be evaluated
  141. // for its potential side effects.
  142. return E->getType()->isNullPtrType();
  143. }
  144. /// If \p E is a widened promoted integer, get its base (unpromoted) type.
  145. static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
  146. const Expr *E) {
  147. const Expr *Base = E->IgnoreImpCasts();
  148. if (E == Base)
  149. return llvm::None;
  150. QualType BaseTy = Base->getType();
  151. if (!BaseTy->isPromotableIntegerType() ||
  152. Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
  153. return llvm::None;
  154. return BaseTy;
  155. }
  156. /// Check if \p E is a widened promoted integer.
  157. static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
  158. return getUnwidenedIntegerType(Ctx, E).hasValue();
  159. }
  160. /// Check if we can skip the overflow check for \p Op.
  161. static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
  162. assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
  163. "Expected a unary or binary operator");
  164. // If the binop has constant inputs and we can prove there is no overflow,
  165. // we can elide the overflow check.
  166. if (!Op.mayHaveIntegerOverflow())
  167. return true;
  168. // If a unary op has a widened operand, the op cannot overflow.
  169. if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
  170. return !UO->canOverflow();
  171. // We usually don't need overflow checks for binops with widened operands.
  172. // Multiplication with promoted unsigned operands is a special case.
  173. const auto *BO = cast<BinaryOperator>(Op.E);
  174. auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
  175. if (!OptionalLHSTy)
  176. return false;
  177. auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
  178. if (!OptionalRHSTy)
  179. return false;
  180. QualType LHSTy = *OptionalLHSTy;
  181. QualType RHSTy = *OptionalRHSTy;
  182. // This is the simple case: binops without unsigned multiplication, and with
  183. // widened operands. No overflow check is needed here.
  184. if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
  185. !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
  186. return true;
  187. // For unsigned multiplication the overflow check can be elided if either one
  188. // of the unpromoted types are less than half the size of the promoted type.
  189. unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
  190. return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
  191. (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
  192. }
  193. class ScalarExprEmitter
  194. : public StmtVisitor<ScalarExprEmitter, Value*> {
  195. CodeGenFunction &CGF;
  196. CGBuilderTy &Builder;
  197. bool IgnoreResultAssign;
  198. llvm::LLVMContext &VMContext;
  199. public:
  200. ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
  201. : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
  202. VMContext(cgf.getLLVMContext()) {
  203. }
  204. //===--------------------------------------------------------------------===//
  205. // Utilities
  206. //===--------------------------------------------------------------------===//
  207. bool TestAndClearIgnoreResultAssign() {
  208. bool I = IgnoreResultAssign;
  209. IgnoreResultAssign = false;
  210. return I;
  211. }
  212. llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
  213. LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
  214. LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
  215. return CGF.EmitCheckedLValue(E, TCK);
  216. }
  217. void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
  218. const BinOpInfo &Info);
  219. Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  220. return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
  221. }
  222. void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
  223. const AlignValueAttr *AVAttr = nullptr;
  224. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  225. const ValueDecl *VD = DRE->getDecl();
  226. if (VD->getType()->isReferenceType()) {
  227. if (const auto *TTy =
  228. dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
  229. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  230. } else {
  231. // Assumptions for function parameters are emitted at the start of the
  232. // function, so there is no need to repeat that here,
  233. // unless the alignment-assumption sanitizer is enabled,
  234. // then we prefer the assumption over alignment attribute
  235. // on IR function param.
  236. if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
  237. return;
  238. AVAttr = VD->getAttr<AlignValueAttr>();
  239. }
  240. }
  241. if (!AVAttr)
  242. if (const auto *TTy =
  243. dyn_cast<TypedefType>(E->getType()))
  244. AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
  245. if (!AVAttr)
  246. return;
  247. Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
  248. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
  249. CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
  250. }
  251. /// EmitLoadOfLValue - Given an expression with complex type that represents a
  252. /// value l-value, this method emits the address of the l-value, then loads
  253. /// and returns the result.
  254. Value *EmitLoadOfLValue(const Expr *E) {
  255. Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
  256. E->getExprLoc());
  257. EmitLValueAlignmentAssumption(E, V);
  258. return V;
  259. }
  260. /// EmitConversionToBool - Convert the specified expression value to a
  261. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  262. Value *EmitConversionToBool(Value *Src, QualType DstTy);
  263. /// Emit a check that a conversion from a floating-point type does not
  264. /// overflow.
  265. void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
  266. Value *Src, QualType SrcType, QualType DstType,
  267. llvm::Type *DstTy, SourceLocation Loc);
  268. /// Known implicit conversion check kinds.
  269. /// Keep in sync with the enum of the same name in ubsan_handlers.h
  270. enum ImplicitConversionCheckKind : unsigned char {
  271. ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
  272. ICCK_UnsignedIntegerTruncation = 1,
  273. ICCK_SignedIntegerTruncation = 2,
  274. ICCK_IntegerSignChange = 3,
  275. ICCK_SignedIntegerTruncationOrSignChange = 4,
  276. };
  277. /// Emit a check that an [implicit] truncation of an integer does not
  278. /// discard any bits. It is not UB, so we use the value after truncation.
  279. void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
  280. QualType DstType, SourceLocation Loc);
  281. /// Emit a check that an [implicit] conversion of an integer does not change
  282. /// the sign of the value. It is not UB, so we use the value after conversion.
  283. /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
  284. void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
  285. QualType DstType, SourceLocation Loc);
  286. /// Emit a conversion from the specified type to the specified destination
  287. /// type, both of which are LLVM scalar types.
  288. struct ScalarConversionOpts {
  289. bool TreatBooleanAsSigned;
  290. bool EmitImplicitIntegerTruncationChecks;
  291. bool EmitImplicitIntegerSignChangeChecks;
  292. ScalarConversionOpts()
  293. : TreatBooleanAsSigned(false),
  294. EmitImplicitIntegerTruncationChecks(false),
  295. EmitImplicitIntegerSignChangeChecks(false) {}
  296. ScalarConversionOpts(clang::SanitizerSet SanOpts)
  297. : TreatBooleanAsSigned(false),
  298. EmitImplicitIntegerTruncationChecks(
  299. SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
  300. EmitImplicitIntegerSignChangeChecks(
  301. SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
  302. };
  303. Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
  304. llvm::Type *SrcTy, llvm::Type *DstTy,
  305. ScalarConversionOpts Opts);
  306. Value *
  307. EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
  308. SourceLocation Loc,
  309. ScalarConversionOpts Opts = ScalarConversionOpts());
  310. /// Convert between either a fixed point and other fixed point or fixed point
  311. /// and an integer.
  312. Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
  313. SourceLocation Loc);
  314. /// Emit a conversion from the specified complex type to the specified
  315. /// destination type, where the destination type is an LLVM scalar type.
  316. Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
  317. QualType SrcTy, QualType DstTy,
  318. SourceLocation Loc);
  319. /// EmitNullValue - Emit a value that corresponds to null for the given type.
  320. Value *EmitNullValue(QualType Ty);
  321. /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
  322. Value *EmitFloatToBoolConversion(Value *V) {
  323. // Compare against 0.0 for fp scalars.
  324. llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
  325. return Builder.CreateFCmpUNE(V, Zero, "tobool");
  326. }
  327. /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
  328. Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
  329. Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
  330. return Builder.CreateICmpNE(V, Zero, "tobool");
  331. }
  332. Value *EmitIntToBoolConversion(Value *V) {
  333. // Because of the type rules of C, we often end up computing a
  334. // logical value, then zero extending it to int, then wanting it
  335. // as a logical value again. Optimize this common case.
  336. if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
  337. if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
  338. Value *Result = ZI->getOperand(0);
  339. // If there aren't any more uses, zap the instruction to save space.
  340. // Note that there can be more uses, for example if this
  341. // is the result of an assignment.
  342. if (ZI->use_empty())
  343. ZI->eraseFromParent();
  344. return Result;
  345. }
  346. }
  347. return Builder.CreateIsNotNull(V, "tobool");
  348. }
  349. //===--------------------------------------------------------------------===//
  350. // Visitor Methods
  351. //===--------------------------------------------------------------------===//
  352. Value *Visit(Expr *E) {
  353. ApplyDebugLocation DL(CGF, E);
  354. return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
  355. }
  356. Value *VisitStmt(Stmt *S) {
  357. S->dump(llvm::errs(), CGF.getContext());
  358. llvm_unreachable("Stmt can't have complex result type!");
  359. }
  360. Value *VisitExpr(Expr *S);
  361. Value *VisitConstantExpr(ConstantExpr *E) {
  362. // A constant expression of type 'void' generates no code and produces no
  363. // value.
  364. if (E->getType()->isVoidType())
  365. return nullptr;
  366. if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
  367. if (E->isGLValue())
  368. return CGF.Builder.CreateLoad(Address(
  369. Result, CGF.getContext().getTypeAlignInChars(E->getType())));
  370. return Result;
  371. }
  372. return Visit(E->getSubExpr());
  373. }
  374. Value *VisitParenExpr(ParenExpr *PE) {
  375. return Visit(PE->getSubExpr());
  376. }
  377. Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  378. return Visit(E->getReplacement());
  379. }
  380. Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  381. return Visit(GE->getResultExpr());
  382. }
  383. Value *VisitCoawaitExpr(CoawaitExpr *S) {
  384. return CGF.EmitCoawaitExpr(*S).getScalarVal();
  385. }
  386. Value *VisitCoyieldExpr(CoyieldExpr *S) {
  387. return CGF.EmitCoyieldExpr(*S).getScalarVal();
  388. }
  389. Value *VisitUnaryCoawait(const UnaryOperator *E) {
  390. return Visit(E->getSubExpr());
  391. }
  392. // Leaves.
  393. Value *VisitIntegerLiteral(const IntegerLiteral *E) {
  394. return Builder.getInt(E->getValue());
  395. }
  396. Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
  397. return Builder.getInt(E->getValue());
  398. }
  399. Value *VisitFloatingLiteral(const FloatingLiteral *E) {
  400. return llvm::ConstantFP::get(VMContext, E->getValue());
  401. }
  402. Value *VisitCharacterLiteral(const CharacterLiteral *E) {
  403. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  404. }
  405. Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  406. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  407. }
  408. Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  409. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  410. }
  411. Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  412. return EmitNullValue(E->getType());
  413. }
  414. Value *VisitGNUNullExpr(const GNUNullExpr *E) {
  415. return EmitNullValue(E->getType());
  416. }
  417. Value *VisitOffsetOfExpr(OffsetOfExpr *E);
  418. Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  419. Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
  420. llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
  421. return Builder.CreateBitCast(V, ConvertType(E->getType()));
  422. }
  423. Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
  424. return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
  425. }
  426. Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  427. return CGF.EmitPseudoObjectRValue(E).getScalarVal();
  428. }
  429. Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
  430. Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  431. if (E->isGLValue())
  432. return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
  433. E->getExprLoc());
  434. // Otherwise, assume the mapping is the scalar directly.
  435. return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
  436. }
  437. // l-values.
  438. Value *VisitDeclRefExpr(DeclRefExpr *E) {
  439. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
  440. return CGF.emitScalarConstant(Constant, E);
  441. return EmitLoadOfLValue(E);
  442. }
  443. Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
  444. return CGF.EmitObjCSelectorExpr(E);
  445. }
  446. Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
  447. return CGF.EmitObjCProtocolExpr(E);
  448. }
  449. Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  450. return EmitLoadOfLValue(E);
  451. }
  452. Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
  453. if (E->getMethodDecl() &&
  454. E->getMethodDecl()->getReturnType()->isReferenceType())
  455. return EmitLoadOfLValue(E);
  456. return CGF.EmitObjCMessageExpr(E).getScalarVal();
  457. }
  458. Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
  459. LValue LV = CGF.EmitObjCIsaExpr(E);
  460. Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
  461. return V;
  462. }
  463. Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
  464. VersionTuple Version = E->getVersion();
  465. // If we're checking for a platform older than our minimum deployment
  466. // target, we can fold the check away.
  467. if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
  468. return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
  469. return CGF.EmitBuiltinAvailable(Version);
  470. }
  471. Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
  472. Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
  473. Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
  474. Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
  475. Value *VisitMemberExpr(MemberExpr *E);
  476. Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
  477. Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  478. // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
  479. // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
  480. // literals aren't l-values in C++. We do so simply because that's the
  481. // cleanest way to handle compound literals in C++.
  482. // See the discussion here: https://reviews.llvm.org/D64464
  483. return EmitLoadOfLValue(E);
  484. }
  485. Value *VisitInitListExpr(InitListExpr *E);
  486. Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
  487. assert(CGF.getArrayInitIndex() &&
  488. "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
  489. return CGF.getArrayInitIndex();
  490. }
  491. Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  492. return EmitNullValue(E->getType());
  493. }
  494. Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
  495. CGF.CGM.EmitExplicitCastExprType(E, &CGF);
  496. return VisitCastExpr(E);
  497. }
  498. Value *VisitCastExpr(CastExpr *E);
  499. Value *VisitCallExpr(const CallExpr *E) {
  500. if (E->getCallReturnType(CGF.getContext())->isReferenceType())
  501. return EmitLoadOfLValue(E);
  502. Value *V = CGF.EmitCallExpr(E).getScalarVal();
  503. EmitLValueAlignmentAssumption(E, V);
  504. return V;
  505. }
  506. Value *VisitStmtExpr(const StmtExpr *E);
  507. // Unary Operators.
  508. Value *VisitUnaryPostDec(const UnaryOperator *E) {
  509. LValue LV = EmitLValue(E->getSubExpr());
  510. return EmitScalarPrePostIncDec(E, LV, false, false);
  511. }
  512. Value *VisitUnaryPostInc(const UnaryOperator *E) {
  513. LValue LV = EmitLValue(E->getSubExpr());
  514. return EmitScalarPrePostIncDec(E, LV, true, false);
  515. }
  516. Value *VisitUnaryPreDec(const UnaryOperator *E) {
  517. LValue LV = EmitLValue(E->getSubExpr());
  518. return EmitScalarPrePostIncDec(E, LV, false, true);
  519. }
  520. Value *VisitUnaryPreInc(const UnaryOperator *E) {
  521. LValue LV = EmitLValue(E->getSubExpr());
  522. return EmitScalarPrePostIncDec(E, LV, true, true);
  523. }
  524. llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
  525. llvm::Value *InVal,
  526. bool IsInc);
  527. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  528. bool isInc, bool isPre);
  529. Value *VisitUnaryAddrOf(const UnaryOperator *E) {
  530. if (isa<MemberPointerType>(E->getType())) // never sugared
  531. return CGF.CGM.getMemberPointerConstant(E);
  532. return EmitLValue(E->getSubExpr()).getPointer(CGF);
  533. }
  534. Value *VisitUnaryDeref(const UnaryOperator *E) {
  535. if (E->getType()->isVoidType())
  536. return Visit(E->getSubExpr()); // the actual value should be unused
  537. return EmitLoadOfLValue(E);
  538. }
  539. Value *VisitUnaryPlus(const UnaryOperator *E) {
  540. // This differs from gcc, though, most likely due to a bug in gcc.
  541. TestAndClearIgnoreResultAssign();
  542. return Visit(E->getSubExpr());
  543. }
  544. Value *VisitUnaryMinus (const UnaryOperator *E);
  545. Value *VisitUnaryNot (const UnaryOperator *E);
  546. Value *VisitUnaryLNot (const UnaryOperator *E);
  547. Value *VisitUnaryReal (const UnaryOperator *E);
  548. Value *VisitUnaryImag (const UnaryOperator *E);
  549. Value *VisitUnaryExtension(const UnaryOperator *E) {
  550. return Visit(E->getSubExpr());
  551. }
  552. // C++
  553. Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
  554. return EmitLoadOfLValue(E);
  555. }
  556. Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
  557. auto &Ctx = CGF.getContext();
  558. APValue Evaluated =
  559. SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
  560. return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
  561. SLE->getType());
  562. }
  563. Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  564. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  565. return Visit(DAE->getExpr());
  566. }
  567. Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  568. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  569. return Visit(DIE->getExpr());
  570. }
  571. Value *VisitCXXThisExpr(CXXThisExpr *TE) {
  572. return CGF.LoadCXXThis();
  573. }
  574. Value *VisitExprWithCleanups(ExprWithCleanups *E);
  575. Value *VisitCXXNewExpr(const CXXNewExpr *E) {
  576. return CGF.EmitCXXNewExpr(E);
  577. }
  578. Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  579. CGF.EmitCXXDeleteExpr(E);
  580. return nullptr;
  581. }
  582. Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
  583. return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
  584. }
  585. Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
  586. return Builder.getInt1(E->isSatisfied());
  587. }
  588. Value *VisitRequiresExpr(const RequiresExpr *E) {
  589. return Builder.getInt1(E->isSatisfied());
  590. }
  591. Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  592. return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
  593. }
  594. Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  595. return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
  596. }
  597. Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
  598. // C++ [expr.pseudo]p1:
  599. // The result shall only be used as the operand for the function call
  600. // operator (), and the result of such a call has type void. The only
  601. // effect is the evaluation of the postfix-expression before the dot or
  602. // arrow.
  603. CGF.EmitScalarExpr(E->getBase());
  604. return nullptr;
  605. }
  606. Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  607. return EmitNullValue(E->getType());
  608. }
  609. Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
  610. CGF.EmitCXXThrowExpr(E);
  611. return nullptr;
  612. }
  613. Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  614. return Builder.getInt1(E->getValue());
  615. }
  616. // Binary Operators.
  617. Value *EmitMul(const BinOpInfo &Ops) {
  618. if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
  619. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  620. case LangOptions::SOB_Defined:
  621. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  622. case LangOptions::SOB_Undefined:
  623. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  624. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  625. LLVM_FALLTHROUGH;
  626. case LangOptions::SOB_Trapping:
  627. if (CanElideOverflowCheck(CGF.getContext(), Ops))
  628. return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
  629. return EmitOverflowCheckedBinOp(Ops);
  630. }
  631. }
  632. if (Ops.Ty->isConstantMatrixType()) {
  633. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  634. // We need to check the types of the operands of the operator to get the
  635. // correct matrix dimensions.
  636. auto *BO = cast<BinaryOperator>(Ops.E);
  637. auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
  638. BO->getLHS()->getType().getCanonicalType());
  639. auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
  640. BO->getRHS()->getType().getCanonicalType());
  641. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
  642. if (LHSMatTy && RHSMatTy)
  643. return MB.CreateMatrixMultiply(Ops.LHS, Ops.RHS, LHSMatTy->getNumRows(),
  644. LHSMatTy->getNumColumns(),
  645. RHSMatTy->getNumColumns());
  646. return MB.CreateScalarMultiply(Ops.LHS, Ops.RHS);
  647. }
  648. if (Ops.Ty->isUnsignedIntegerType() &&
  649. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  650. !CanElideOverflowCheck(CGF.getContext(), Ops))
  651. return EmitOverflowCheckedBinOp(Ops);
  652. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  653. // Preserve the old values
  654. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
  655. return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
  656. }
  657. if (Ops.isFixedPointOp())
  658. return EmitFixedPointBinOp(Ops);
  659. return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
  660. }
  661. /// Create a binary op that checks for overflow.
  662. /// Currently only supports +, - and *.
  663. Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
  664. // Check for undefined division and modulus behaviors.
  665. void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
  666. llvm::Value *Zero,bool isDiv);
  667. // Common helper for getting how wide LHS of shift is.
  668. static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
  669. // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
  670. // non powers of two.
  671. Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
  672. Value *EmitDiv(const BinOpInfo &Ops);
  673. Value *EmitRem(const BinOpInfo &Ops);
  674. Value *EmitAdd(const BinOpInfo &Ops);
  675. Value *EmitSub(const BinOpInfo &Ops);
  676. Value *EmitShl(const BinOpInfo &Ops);
  677. Value *EmitShr(const BinOpInfo &Ops);
  678. Value *EmitAnd(const BinOpInfo &Ops) {
  679. return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
  680. }
  681. Value *EmitXor(const BinOpInfo &Ops) {
  682. return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
  683. }
  684. Value *EmitOr (const BinOpInfo &Ops) {
  685. return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
  686. }
  687. // Helper functions for fixed point binary operations.
  688. Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
  689. BinOpInfo EmitBinOps(const BinaryOperator *E);
  690. LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
  691. Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
  692. Value *&Result);
  693. Value *EmitCompoundAssign(const CompoundAssignOperator *E,
  694. Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
  695. // Binary operators and binary compound assignment operators.
  696. #define HANDLEBINOP(OP) \
  697. Value *VisitBin ## OP(const BinaryOperator *E) { \
  698. return Emit ## OP(EmitBinOps(E)); \
  699. } \
  700. Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
  701. return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
  702. }
  703. HANDLEBINOP(Mul)
  704. HANDLEBINOP(Div)
  705. HANDLEBINOP(Rem)
  706. HANDLEBINOP(Add)
  707. HANDLEBINOP(Sub)
  708. HANDLEBINOP(Shl)
  709. HANDLEBINOP(Shr)
  710. HANDLEBINOP(And)
  711. HANDLEBINOP(Xor)
  712. HANDLEBINOP(Or)
  713. #undef HANDLEBINOP
  714. // Comparisons.
  715. Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
  716. llvm::CmpInst::Predicate SICmpOpc,
  717. llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
  718. #define VISITCOMP(CODE, UI, SI, FP, SIG) \
  719. Value *VisitBin##CODE(const BinaryOperator *E) { \
  720. return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
  721. llvm::FCmpInst::FP, SIG); }
  722. VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
  723. VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
  724. VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
  725. VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
  726. VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
  727. VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
  728. #undef VISITCOMP
  729. Value *VisitBinAssign (const BinaryOperator *E);
  730. Value *VisitBinLAnd (const BinaryOperator *E);
  731. Value *VisitBinLOr (const BinaryOperator *E);
  732. Value *VisitBinComma (const BinaryOperator *E);
  733. Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
  734. Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
  735. Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
  736. return Visit(E->getSemanticForm());
  737. }
  738. // Other Operators.
  739. Value *VisitBlockExpr(const BlockExpr *BE);
  740. Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
  741. Value *VisitChooseExpr(ChooseExpr *CE);
  742. Value *VisitVAArgExpr(VAArgExpr *VE);
  743. Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
  744. return CGF.EmitObjCStringLiteral(E);
  745. }
  746. Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
  747. return CGF.EmitObjCBoxedExpr(E);
  748. }
  749. Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
  750. return CGF.EmitObjCArrayLiteral(E);
  751. }
  752. Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  753. return CGF.EmitObjCDictionaryLiteral(E);
  754. }
  755. Value *VisitAsTypeExpr(AsTypeExpr *CE);
  756. Value *VisitAtomicExpr(AtomicExpr *AE);
  757. };
  758. } // end anonymous namespace.
  759. //===----------------------------------------------------------------------===//
  760. // Utilities
  761. //===----------------------------------------------------------------------===//
  762. /// EmitConversionToBool - Convert the specified expression value to a
  763. /// boolean (i1) truth value. This is equivalent to "Val != 0".
  764. Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
  765. assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
  766. if (SrcType->isRealFloatingType())
  767. return EmitFloatToBoolConversion(Src);
  768. if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
  769. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
  770. assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
  771. "Unknown scalar type to convert");
  772. if (isa<llvm::IntegerType>(Src->getType()))
  773. return EmitIntToBoolConversion(Src);
  774. assert(isa<llvm::PointerType>(Src->getType()));
  775. return EmitPointerToBoolConversion(Src, SrcType);
  776. }
  777. void ScalarExprEmitter::EmitFloatConversionCheck(
  778. Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
  779. QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
  780. assert(SrcType->isFloatingType() && "not a conversion from floating point");
  781. if (!isa<llvm::IntegerType>(DstTy))
  782. return;
  783. CodeGenFunction::SanitizerScope SanScope(&CGF);
  784. using llvm::APFloat;
  785. using llvm::APSInt;
  786. llvm::Value *Check = nullptr;
  787. const llvm::fltSemantics &SrcSema =
  788. CGF.getContext().getFloatTypeSemantics(OrigSrcType);
  789. // Floating-point to integer. This has undefined behavior if the source is
  790. // +-Inf, NaN, or doesn't fit into the destination type (after truncation
  791. // to an integer).
  792. unsigned Width = CGF.getContext().getIntWidth(DstType);
  793. bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
  794. APSInt Min = APSInt::getMinValue(Width, Unsigned);
  795. APFloat MinSrc(SrcSema, APFloat::uninitialized);
  796. if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
  797. APFloat::opOverflow)
  798. // Don't need an overflow check for lower bound. Just check for
  799. // -Inf/NaN.
  800. MinSrc = APFloat::getInf(SrcSema, true);
  801. else
  802. // Find the largest value which is too small to represent (before
  803. // truncation toward zero).
  804. MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
  805. APSInt Max = APSInt::getMaxValue(Width, Unsigned);
  806. APFloat MaxSrc(SrcSema, APFloat::uninitialized);
  807. if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
  808. APFloat::opOverflow)
  809. // Don't need an overflow check for upper bound. Just check for
  810. // +Inf/NaN.
  811. MaxSrc = APFloat::getInf(SrcSema, false);
  812. else
  813. // Find the smallest value which is too large to represent (before
  814. // truncation toward zero).
  815. MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
  816. // If we're converting from __half, convert the range to float to match
  817. // the type of src.
  818. if (OrigSrcType->isHalfType()) {
  819. const llvm::fltSemantics &Sema =
  820. CGF.getContext().getFloatTypeSemantics(SrcType);
  821. bool IsInexact;
  822. MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  823. MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
  824. }
  825. llvm::Value *GE =
  826. Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
  827. llvm::Value *LE =
  828. Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
  829. Check = Builder.CreateAnd(GE, LE);
  830. llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
  831. CGF.EmitCheckTypeDescriptor(OrigSrcType),
  832. CGF.EmitCheckTypeDescriptor(DstType)};
  833. CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
  834. SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
  835. }
  836. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  837. // Returns 'i1 false' when the truncation Src -> Dst was lossy.
  838. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  839. std::pair<llvm::Value *, SanitizerMask>>
  840. EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  841. QualType DstType, CGBuilderTy &Builder) {
  842. llvm::Type *SrcTy = Src->getType();
  843. llvm::Type *DstTy = Dst->getType();
  844. (void)DstTy; // Only used in assert()
  845. // This should be truncation of integral types.
  846. assert(Src != Dst);
  847. assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
  848. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  849. "non-integer llvm type");
  850. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  851. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  852. // If both (src and dst) types are unsigned, then it's an unsigned truncation.
  853. // Else, it is a signed truncation.
  854. ScalarExprEmitter::ImplicitConversionCheckKind Kind;
  855. SanitizerMask Mask;
  856. if (!SrcSigned && !DstSigned) {
  857. Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
  858. Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
  859. } else {
  860. Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
  861. Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
  862. }
  863. llvm::Value *Check = nullptr;
  864. // 1. Extend the truncated value back to the same width as the Src.
  865. Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
  866. // 2. Equality-compare with the original source value
  867. Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
  868. // If the comparison result is 'i1 false', then the truncation was lossy.
  869. return std::make_pair(Kind, std::make_pair(Check, Mask));
  870. }
  871. static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
  872. QualType SrcType, QualType DstType) {
  873. return SrcType->isIntegerType() && DstType->isIntegerType();
  874. }
  875. void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
  876. Value *Dst, QualType DstType,
  877. SourceLocation Loc) {
  878. if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
  879. return;
  880. // We only care about int->int conversions here.
  881. // We ignore conversions to/from pointer and/or bool.
  882. if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
  883. DstType))
  884. return;
  885. unsigned SrcBits = Src->getType()->getScalarSizeInBits();
  886. unsigned DstBits = Dst->getType()->getScalarSizeInBits();
  887. // This must be truncation. Else we do not care.
  888. if (SrcBits <= DstBits)
  889. return;
  890. assert(!DstType->isBooleanType() && "we should not get here with booleans.");
  891. // If the integer sign change sanitizer is enabled,
  892. // and we are truncating from larger unsigned type to smaller signed type,
  893. // let that next sanitizer deal with it.
  894. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  895. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  896. if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
  897. (!SrcSigned && DstSigned))
  898. return;
  899. CodeGenFunction::SanitizerScope SanScope(&CGF);
  900. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  901. std::pair<llvm::Value *, SanitizerMask>>
  902. Check =
  903. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  904. // If the comparison result is 'i1 false', then the truncation was lossy.
  905. // Do we care about this type of truncation?
  906. if (!CGF.SanOpts.has(Check.second.second))
  907. return;
  908. llvm::Constant *StaticArgs[] = {
  909. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  910. CGF.EmitCheckTypeDescriptor(DstType),
  911. llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
  912. CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
  913. {Src, Dst});
  914. }
  915. // Should be called within CodeGenFunction::SanitizerScope RAII scope.
  916. // Returns 'i1 false' when the conversion Src -> Dst changed the sign.
  917. static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  918. std::pair<llvm::Value *, SanitizerMask>>
  919. EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
  920. QualType DstType, CGBuilderTy &Builder) {
  921. llvm::Type *SrcTy = Src->getType();
  922. llvm::Type *DstTy = Dst->getType();
  923. assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
  924. "non-integer llvm type");
  925. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  926. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  927. (void)SrcSigned; // Only used in assert()
  928. (void)DstSigned; // Only used in assert()
  929. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  930. unsigned DstBits = DstTy->getScalarSizeInBits();
  931. (void)SrcBits; // Only used in assert()
  932. (void)DstBits; // Only used in assert()
  933. assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
  934. "either the widths should be different, or the signednesses.");
  935. // NOTE: zero value is considered to be non-negative.
  936. auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
  937. const char *Name) -> Value * {
  938. // Is this value a signed type?
  939. bool VSigned = VType->isSignedIntegerOrEnumerationType();
  940. llvm::Type *VTy = V->getType();
  941. if (!VSigned) {
  942. // If the value is unsigned, then it is never negative.
  943. // FIXME: can we encounter non-scalar VTy here?
  944. return llvm::ConstantInt::getFalse(VTy->getContext());
  945. }
  946. // Get the zero of the same type with which we will be comparing.
  947. llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
  948. // %V.isnegative = icmp slt %V, 0
  949. // I.e is %V *strictly* less than zero, does it have negative value?
  950. return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
  951. llvm::Twine(Name) + "." + V->getName() +
  952. ".negativitycheck");
  953. };
  954. // 1. Was the old Value negative?
  955. llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
  956. // 2. Is the new Value negative?
  957. llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
  958. // 3. Now, was the 'negativity status' preserved during the conversion?
  959. // NOTE: conversion from negative to zero is considered to change the sign.
  960. // (We want to get 'false' when the conversion changed the sign)
  961. // So we should just equality-compare the negativity statuses.
  962. llvm::Value *Check = nullptr;
  963. Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
  964. // If the comparison result is 'false', then the conversion changed the sign.
  965. return std::make_pair(
  966. ScalarExprEmitter::ICCK_IntegerSignChange,
  967. std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
  968. }
  969. void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
  970. Value *Dst, QualType DstType,
  971. SourceLocation Loc) {
  972. if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
  973. return;
  974. llvm::Type *SrcTy = Src->getType();
  975. llvm::Type *DstTy = Dst->getType();
  976. // We only care about int->int conversions here.
  977. // We ignore conversions to/from pointer and/or bool.
  978. if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
  979. DstType))
  980. return;
  981. bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
  982. bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
  983. unsigned SrcBits = SrcTy->getScalarSizeInBits();
  984. unsigned DstBits = DstTy->getScalarSizeInBits();
  985. // Now, we do not need to emit the check in *all* of the cases.
  986. // We can avoid emitting it in some obvious cases where it would have been
  987. // dropped by the opt passes (instcombine) always anyways.
  988. // If it's a cast between effectively the same type, no check.
  989. // NOTE: this is *not* equivalent to checking the canonical types.
  990. if (SrcSigned == DstSigned && SrcBits == DstBits)
  991. return;
  992. // At least one of the values needs to have signed type.
  993. // If both are unsigned, then obviously, neither of them can be negative.
  994. if (!SrcSigned && !DstSigned)
  995. return;
  996. // If the conversion is to *larger* *signed* type, then no check is needed.
  997. // Because either sign-extension happens (so the sign will remain),
  998. // or zero-extension will happen (the sign bit will be zero.)
  999. if ((DstBits > SrcBits) && DstSigned)
  1000. return;
  1001. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  1002. (SrcBits > DstBits) && SrcSigned) {
  1003. // If the signed integer truncation sanitizer is enabled,
  1004. // and this is a truncation from signed type, then no check is needed.
  1005. // Because here sign change check is interchangeable with truncation check.
  1006. return;
  1007. }
  1008. // That's it. We can't rule out any more cases with the data we have.
  1009. CodeGenFunction::SanitizerScope SanScope(&CGF);
  1010. std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
  1011. std::pair<llvm::Value *, SanitizerMask>>
  1012. Check;
  1013. // Each of these checks needs to return 'false' when an issue was detected.
  1014. ImplicitConversionCheckKind CheckKind;
  1015. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  1016. // So we can 'and' all the checks together, and still get 'false',
  1017. // if at least one of the checks detected an issue.
  1018. Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
  1019. CheckKind = Check.first;
  1020. Checks.emplace_back(Check.second);
  1021. if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
  1022. (SrcBits > DstBits) && !SrcSigned && DstSigned) {
  1023. // If the signed integer truncation sanitizer was enabled,
  1024. // and we are truncating from larger unsigned type to smaller signed type,
  1025. // let's handle the case we skipped in that check.
  1026. Check =
  1027. EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
  1028. CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
  1029. Checks.emplace_back(Check.second);
  1030. // If the comparison result is 'i1 false', then the truncation was lossy.
  1031. }
  1032. llvm::Constant *StaticArgs[] = {
  1033. CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
  1034. CGF.EmitCheckTypeDescriptor(DstType),
  1035. llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
  1036. // EmitCheck() will 'and' all the checks together.
  1037. CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
  1038. {Src, Dst});
  1039. }
  1040. Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
  1041. QualType DstType, llvm::Type *SrcTy,
  1042. llvm::Type *DstTy,
  1043. ScalarConversionOpts Opts) {
  1044. // The Element types determine the type of cast to perform.
  1045. llvm::Type *SrcElementTy;
  1046. llvm::Type *DstElementTy;
  1047. QualType SrcElementType;
  1048. QualType DstElementType;
  1049. if (SrcType->isMatrixType() && DstType->isMatrixType()) {
  1050. SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
  1051. DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
  1052. SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
  1053. DstElementType = DstType->castAs<MatrixType>()->getElementType();
  1054. } else {
  1055. assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
  1056. "cannot cast between matrix and non-matrix types");
  1057. SrcElementTy = SrcTy;
  1058. DstElementTy = DstTy;
  1059. SrcElementType = SrcType;
  1060. DstElementType = DstType;
  1061. }
  1062. if (isa<llvm::IntegerType>(SrcElementTy)) {
  1063. bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
  1064. if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
  1065. InputSigned = true;
  1066. }
  1067. if (isa<llvm::IntegerType>(DstElementTy))
  1068. return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1069. if (InputSigned)
  1070. return Builder.CreateSIToFP(Src, DstTy, "conv");
  1071. return Builder.CreateUIToFP(Src, DstTy, "conv");
  1072. }
  1073. if (isa<llvm::IntegerType>(DstElementTy)) {
  1074. assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
  1075. bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
  1076. // If we can't recognize overflow as undefined behavior, assume that
  1077. // overflow saturates. This protects against normal optimizations if we are
  1078. // compiling with non-standard FP semantics.
  1079. if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
  1080. llvm::Intrinsic::ID IID =
  1081. IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
  1082. return Builder.CreateCall(CGF.CGM.getIntrinsic(IID, {DstTy, SrcTy}), Src);
  1083. }
  1084. if (IsSigned)
  1085. return Builder.CreateFPToSI(Src, DstTy, "conv");
  1086. return Builder.CreateFPToUI(Src, DstTy, "conv");
  1087. }
  1088. if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
  1089. return Builder.CreateFPTrunc(Src, DstTy, "conv");
  1090. return Builder.CreateFPExt(Src, DstTy, "conv");
  1091. }
  1092. /// Emit a conversion from the specified type to the specified destination type,
  1093. /// both of which are LLVM scalar types.
  1094. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
  1095. QualType DstType,
  1096. SourceLocation Loc,
  1097. ScalarConversionOpts Opts) {
  1098. // All conversions involving fixed point types should be handled by the
  1099. // EmitFixedPoint family functions. This is done to prevent bloating up this
  1100. // function more, and although fixed point numbers are represented by
  1101. // integers, we do not want to follow any logic that assumes they should be
  1102. // treated as integers.
  1103. // TODO(leonardchan): When necessary, add another if statement checking for
  1104. // conversions to fixed point types from other types.
  1105. if (SrcType->isFixedPointType()) {
  1106. if (DstType->isBooleanType())
  1107. // It is important that we check this before checking if the dest type is
  1108. // an integer because booleans are technically integer types.
  1109. // We do not need to check the padding bit on unsigned types if unsigned
  1110. // padding is enabled because overflow into this bit is undefined
  1111. // behavior.
  1112. return Builder.CreateIsNotNull(Src, "tobool");
  1113. if (DstType->isFixedPointType() || DstType->isIntegerType() ||
  1114. DstType->isRealFloatingType())
  1115. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1116. llvm_unreachable(
  1117. "Unhandled scalar conversion from a fixed point type to another type.");
  1118. } else if (DstType->isFixedPointType()) {
  1119. if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
  1120. // This also includes converting booleans and enums to fixed point types.
  1121. return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
  1122. llvm_unreachable(
  1123. "Unhandled scalar conversion to a fixed point type from another type.");
  1124. }
  1125. QualType NoncanonicalSrcType = SrcType;
  1126. QualType NoncanonicalDstType = DstType;
  1127. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1128. DstType = CGF.getContext().getCanonicalType(DstType);
  1129. if (SrcType == DstType) return Src;
  1130. if (DstType->isVoidType()) return nullptr;
  1131. llvm::Value *OrigSrc = Src;
  1132. QualType OrigSrcType = SrcType;
  1133. llvm::Type *SrcTy = Src->getType();
  1134. // Handle conversions to bool first, they are special: comparisons against 0.
  1135. if (DstType->isBooleanType())
  1136. return EmitConversionToBool(Src, SrcType);
  1137. llvm::Type *DstTy = ConvertType(DstType);
  1138. // Cast from half through float if half isn't a native type.
  1139. if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1140. // Cast to FP using the intrinsic if the half type itself isn't supported.
  1141. if (DstTy->isFloatingPointTy()) {
  1142. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1143. return Builder.CreateCall(
  1144. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
  1145. Src);
  1146. } else {
  1147. // Cast to other types through float, using either the intrinsic or FPExt,
  1148. // depending on whether the half type itself is supported
  1149. // (as opposed to operations on half, available with NativeHalfType).
  1150. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1151. Src = Builder.CreateCall(
  1152. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  1153. CGF.CGM.FloatTy),
  1154. Src);
  1155. } else {
  1156. Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
  1157. }
  1158. SrcType = CGF.getContext().FloatTy;
  1159. SrcTy = CGF.FloatTy;
  1160. }
  1161. }
  1162. // Ignore conversions like int -> uint.
  1163. if (SrcTy == DstTy) {
  1164. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1165. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
  1166. NoncanonicalDstType, Loc);
  1167. return Src;
  1168. }
  1169. // Handle pointer conversions next: pointers can only be converted to/from
  1170. // other pointers and integers. Check for pointer types in terms of LLVM, as
  1171. // some native types (like Obj-C id) may map to a pointer type.
  1172. if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
  1173. // The source value may be an integer, or a pointer.
  1174. if (isa<llvm::PointerType>(SrcTy))
  1175. return Builder.CreateBitCast(Src, DstTy, "conv");
  1176. assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
  1177. // First, convert to the correct width so that we control the kind of
  1178. // extension.
  1179. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
  1180. bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
  1181. llvm::Value* IntResult =
  1182. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1183. // Then, cast to pointer.
  1184. return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
  1185. }
  1186. if (isa<llvm::PointerType>(SrcTy)) {
  1187. // Must be an ptr to int cast.
  1188. assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
  1189. return Builder.CreatePtrToInt(Src, DstTy, "conv");
  1190. }
  1191. // A scalar can be splatted to an extended vector of the same element type
  1192. if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
  1193. // Sema should add casts to make sure that the source expression's type is
  1194. // the same as the vector's element type (sans qualifiers)
  1195. assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
  1196. SrcType.getTypePtr() &&
  1197. "Splatted expr doesn't match with vector element type?");
  1198. // Splat the element across to all elements
  1199. unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
  1200. return Builder.CreateVectorSplat(NumElements, Src, "splat");
  1201. }
  1202. if (SrcType->isMatrixType() && DstType->isMatrixType())
  1203. return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
  1204. if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
  1205. // Allow bitcast from vector to integer/fp of the same size.
  1206. unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
  1207. unsigned DstSize = DstTy->getPrimitiveSizeInBits();
  1208. if (SrcSize == DstSize)
  1209. return Builder.CreateBitCast(Src, DstTy, "conv");
  1210. // Conversions between vectors of different sizes are not allowed except
  1211. // when vectors of half are involved. Operations on storage-only half
  1212. // vectors require promoting half vector operands to float vectors and
  1213. // truncating the result, which is either an int or float vector, to a
  1214. // short or half vector.
  1215. // Source and destination are both expected to be vectors.
  1216. llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
  1217. llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
  1218. (void)DstElementTy;
  1219. assert(((SrcElementTy->isIntegerTy() &&
  1220. DstElementTy->isIntegerTy()) ||
  1221. (SrcElementTy->isFloatingPointTy() &&
  1222. DstElementTy->isFloatingPointTy())) &&
  1223. "unexpected conversion between a floating-point vector and an "
  1224. "integer vector");
  1225. // Truncate an i32 vector to an i16 vector.
  1226. if (SrcElementTy->isIntegerTy())
  1227. return Builder.CreateIntCast(Src, DstTy, false, "conv");
  1228. // Truncate a float vector to a half vector.
  1229. if (SrcSize > DstSize)
  1230. return Builder.CreateFPTrunc(Src, DstTy, "conv");
  1231. // Promote a half vector to a float vector.
  1232. return Builder.CreateFPExt(Src, DstTy, "conv");
  1233. }
  1234. // Finally, we have the arithmetic types: real int/float.
  1235. Value *Res = nullptr;
  1236. llvm::Type *ResTy = DstTy;
  1237. // An overflowing conversion has undefined behavior if either the source type
  1238. // or the destination type is a floating-point type. However, we consider the
  1239. // range of representable values for all floating-point types to be
  1240. // [-inf,+inf], so no overflow can ever happen when the destination type is a
  1241. // floating-point type.
  1242. if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
  1243. OrigSrcType->isFloatingType())
  1244. EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
  1245. Loc);
  1246. // Cast to half through float if half isn't a native type.
  1247. if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  1248. // Make sure we cast in a single step if from another FP type.
  1249. if (SrcTy->isFloatingPointTy()) {
  1250. // Use the intrinsic if the half type itself isn't supported
  1251. // (as opposed to operations on half, available with NativeHalfType).
  1252. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1253. return Builder.CreateCall(
  1254. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
  1255. // If the half type is supported, just use an fptrunc.
  1256. return Builder.CreateFPTrunc(Src, DstTy);
  1257. }
  1258. DstTy = CGF.FloatTy;
  1259. }
  1260. Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
  1261. if (DstTy != ResTy) {
  1262. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  1263. assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
  1264. Res = Builder.CreateCall(
  1265. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
  1266. Res);
  1267. } else {
  1268. Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
  1269. }
  1270. }
  1271. if (Opts.EmitImplicitIntegerTruncationChecks)
  1272. EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
  1273. NoncanonicalDstType, Loc);
  1274. if (Opts.EmitImplicitIntegerSignChangeChecks)
  1275. EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
  1276. NoncanonicalDstType, Loc);
  1277. return Res;
  1278. }
  1279. Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
  1280. QualType DstTy,
  1281. SourceLocation Loc) {
  1282. llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
  1283. llvm::Value *Result;
  1284. if (SrcTy->isRealFloatingType())
  1285. Result = FPBuilder.CreateFloatingToFixed(Src,
  1286. CGF.getContext().getFixedPointSemantics(DstTy));
  1287. else if (DstTy->isRealFloatingType())
  1288. Result = FPBuilder.CreateFixedToFloating(Src,
  1289. CGF.getContext().getFixedPointSemantics(SrcTy),
  1290. ConvertType(DstTy));
  1291. else {
  1292. auto SrcFPSema = CGF.getContext().getFixedPointSemantics(SrcTy);
  1293. auto DstFPSema = CGF.getContext().getFixedPointSemantics(DstTy);
  1294. if (DstTy->isIntegerType())
  1295. Result = FPBuilder.CreateFixedToInteger(Src, SrcFPSema,
  1296. DstFPSema.getWidth(),
  1297. DstFPSema.isSigned());
  1298. else if (SrcTy->isIntegerType())
  1299. Result = FPBuilder.CreateIntegerToFixed(Src, SrcFPSema.isSigned(),
  1300. DstFPSema);
  1301. else
  1302. Result = FPBuilder.CreateFixedToFixed(Src, SrcFPSema, DstFPSema);
  1303. }
  1304. return Result;
  1305. }
  1306. /// Emit a conversion from the specified complex type to the specified
  1307. /// destination type, where the destination type is an LLVM scalar type.
  1308. Value *ScalarExprEmitter::EmitComplexToScalarConversion(
  1309. CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
  1310. SourceLocation Loc) {
  1311. // Get the source element type.
  1312. SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
  1313. // Handle conversions to bool first, they are special: comparisons against 0.
  1314. if (DstTy->isBooleanType()) {
  1315. // Complex != 0 -> (Real != 0) | (Imag != 0)
  1316. Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1317. Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
  1318. return Builder.CreateOr(Src.first, Src.second, "tobool");
  1319. }
  1320. // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
  1321. // the imaginary part of the complex value is discarded and the value of the
  1322. // real part is converted according to the conversion rules for the
  1323. // corresponding real type.
  1324. return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
  1325. }
  1326. Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
  1327. return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
  1328. }
  1329. /// Emit a sanitization check for the given "binary" operation (which
  1330. /// might actually be a unary increment which has been lowered to a binary
  1331. /// operation). The check passes if all values in \p Checks (which are \c i1),
  1332. /// are \c true.
  1333. void ScalarExprEmitter::EmitBinOpCheck(
  1334. ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
  1335. assert(CGF.IsSanitizerScope);
  1336. SanitizerHandler Check;
  1337. SmallVector<llvm::Constant *, 4> StaticData;
  1338. SmallVector<llvm::Value *, 2> DynamicData;
  1339. BinaryOperatorKind Opcode = Info.Opcode;
  1340. if (BinaryOperator::isCompoundAssignmentOp(Opcode))
  1341. Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
  1342. StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
  1343. const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
  1344. if (UO && UO->getOpcode() == UO_Minus) {
  1345. Check = SanitizerHandler::NegateOverflow;
  1346. StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
  1347. DynamicData.push_back(Info.RHS);
  1348. } else {
  1349. if (BinaryOperator::isShiftOp(Opcode)) {
  1350. // Shift LHS negative or too large, or RHS out of bounds.
  1351. Check = SanitizerHandler::ShiftOutOfBounds;
  1352. const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
  1353. StaticData.push_back(
  1354. CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
  1355. StaticData.push_back(
  1356. CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
  1357. } else if (Opcode == BO_Div || Opcode == BO_Rem) {
  1358. // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
  1359. Check = SanitizerHandler::DivremOverflow;
  1360. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1361. } else {
  1362. // Arithmetic overflow (+, -, *).
  1363. switch (Opcode) {
  1364. case BO_Add: Check = SanitizerHandler::AddOverflow; break;
  1365. case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
  1366. case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
  1367. default: llvm_unreachable("unexpected opcode for bin op check");
  1368. }
  1369. StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
  1370. }
  1371. DynamicData.push_back(Info.LHS);
  1372. DynamicData.push_back(Info.RHS);
  1373. }
  1374. CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
  1375. }
  1376. //===----------------------------------------------------------------------===//
  1377. // Visitor Methods
  1378. //===----------------------------------------------------------------------===//
  1379. Value *ScalarExprEmitter::VisitExpr(Expr *E) {
  1380. CGF.ErrorUnsupported(E, "scalar expression");
  1381. if (E->getType()->isVoidType())
  1382. return nullptr;
  1383. return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  1384. }
  1385. Value *
  1386. ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
  1387. ASTContext &Context = CGF.getContext();
  1388. llvm::Optional<LangAS> GlobalAS =
  1389. Context.getTargetInfo().getConstantAddressSpace();
  1390. llvm::Constant *GlobalConstStr = Builder.CreateGlobalStringPtr(
  1391. E->ComputeName(Context), "__usn_str",
  1392. static_cast<unsigned>(GlobalAS.getValueOr(LangAS::Default)));
  1393. unsigned ExprAS = Context.getTargetAddressSpace(E->getType());
  1394. if (GlobalConstStr->getType()->getPointerAddressSpace() == ExprAS)
  1395. return GlobalConstStr;
  1396. llvm::PointerType *PtrTy = cast<llvm::PointerType>(GlobalConstStr->getType());
  1397. llvm::PointerType *NewPtrTy =
  1398. llvm::PointerType::getWithSamePointeeType(PtrTy, ExprAS);
  1399. return Builder.CreateAddrSpaceCast(GlobalConstStr, NewPtrTy, "usn_addr_cast");
  1400. }
  1401. Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
  1402. // Vector Mask Case
  1403. if (E->getNumSubExprs() == 2) {
  1404. Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
  1405. Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
  1406. Value *Mask;
  1407. auto *LTy = cast<llvm::FixedVectorType>(LHS->getType());
  1408. unsigned LHSElts = LTy->getNumElements();
  1409. Mask = RHS;
  1410. auto *MTy = cast<llvm::FixedVectorType>(Mask->getType());
  1411. // Mask off the high bits of each shuffle index.
  1412. Value *MaskBits =
  1413. llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
  1414. Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
  1415. // newv = undef
  1416. // mask = mask & maskbits
  1417. // for each elt
  1418. // n = extract mask i
  1419. // x = extract val n
  1420. // newv = insert newv, x, i
  1421. auto *RTy = llvm::FixedVectorType::get(LTy->getElementType(),
  1422. MTy->getNumElements());
  1423. Value* NewV = llvm::UndefValue::get(RTy);
  1424. for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
  1425. Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
  1426. Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
  1427. Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
  1428. NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
  1429. }
  1430. return NewV;
  1431. }
  1432. Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
  1433. Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
  1434. SmallVector<int, 32> Indices;
  1435. for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
  1436. llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
  1437. // Check for -1 and output it as undef in the IR.
  1438. if (Idx.isSigned() && Idx.isAllOnes())
  1439. Indices.push_back(-1);
  1440. else
  1441. Indices.push_back(Idx.getZExtValue());
  1442. }
  1443. return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
  1444. }
  1445. Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
  1446. QualType SrcType = E->getSrcExpr()->getType(),
  1447. DstType = E->getType();
  1448. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  1449. SrcType = CGF.getContext().getCanonicalType(SrcType);
  1450. DstType = CGF.getContext().getCanonicalType(DstType);
  1451. if (SrcType == DstType) return Src;
  1452. assert(SrcType->isVectorType() &&
  1453. "ConvertVector source type must be a vector");
  1454. assert(DstType->isVectorType() &&
  1455. "ConvertVector destination type must be a vector");
  1456. llvm::Type *SrcTy = Src->getType();
  1457. llvm::Type *DstTy = ConvertType(DstType);
  1458. // Ignore conversions like int -> uint.
  1459. if (SrcTy == DstTy)
  1460. return Src;
  1461. QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
  1462. DstEltType = DstType->castAs<VectorType>()->getElementType();
  1463. assert(SrcTy->isVectorTy() &&
  1464. "ConvertVector source IR type must be a vector");
  1465. assert(DstTy->isVectorTy() &&
  1466. "ConvertVector destination IR type must be a vector");
  1467. llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
  1468. *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
  1469. if (DstEltType->isBooleanType()) {
  1470. assert((SrcEltTy->isFloatingPointTy() ||
  1471. isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
  1472. llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
  1473. if (SrcEltTy->isFloatingPointTy()) {
  1474. return Builder.CreateFCmpUNE(Src, Zero, "tobool");
  1475. } else {
  1476. return Builder.CreateICmpNE(Src, Zero, "tobool");
  1477. }
  1478. }
  1479. // We have the arithmetic types: real int/float.
  1480. Value *Res = nullptr;
  1481. if (isa<llvm::IntegerType>(SrcEltTy)) {
  1482. bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
  1483. if (isa<llvm::IntegerType>(DstEltTy))
  1484. Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
  1485. else if (InputSigned)
  1486. Res = Builder.CreateSIToFP(Src, DstTy, "conv");
  1487. else
  1488. Res = Builder.CreateUIToFP(Src, DstTy, "conv");
  1489. } else if (isa<llvm::IntegerType>(DstEltTy)) {
  1490. assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
  1491. if (DstEltType->isSignedIntegerOrEnumerationType())
  1492. Res = Builder.CreateFPToSI(Src, DstTy, "conv");
  1493. else
  1494. Res = Builder.CreateFPToUI(Src, DstTy, "conv");
  1495. } else {
  1496. assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
  1497. "Unknown real conversion");
  1498. if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
  1499. Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
  1500. else
  1501. Res = Builder.CreateFPExt(Src, DstTy, "conv");
  1502. }
  1503. return Res;
  1504. }
  1505. Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
  1506. if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
  1507. CGF.EmitIgnoredExpr(E->getBase());
  1508. return CGF.emitScalarConstant(Constant, E);
  1509. } else {
  1510. Expr::EvalResult Result;
  1511. if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
  1512. llvm::APSInt Value = Result.Val.getInt();
  1513. CGF.EmitIgnoredExpr(E->getBase());
  1514. return Builder.getInt(Value);
  1515. }
  1516. }
  1517. return EmitLoadOfLValue(E);
  1518. }
  1519. Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  1520. TestAndClearIgnoreResultAssign();
  1521. // Emit subscript expressions in rvalue context's. For most cases, this just
  1522. // loads the lvalue formed by the subscript expr. However, we have to be
  1523. // careful, because the base of a vector subscript is occasionally an rvalue,
  1524. // so we can't get it as an lvalue.
  1525. if (!E->getBase()->getType()->isVectorType())
  1526. return EmitLoadOfLValue(E);
  1527. // Handle the vector case. The base must be a vector, the index must be an
  1528. // integer value.
  1529. Value *Base = Visit(E->getBase());
  1530. Value *Idx = Visit(E->getIdx());
  1531. QualType IdxTy = E->getIdx()->getType();
  1532. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  1533. CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
  1534. return Builder.CreateExtractElement(Base, Idx, "vecext");
  1535. }
  1536. Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
  1537. TestAndClearIgnoreResultAssign();
  1538. // Handle the vector case. The base must be a vector, the index must be an
  1539. // integer value.
  1540. Value *RowIdx = Visit(E->getRowIdx());
  1541. Value *ColumnIdx = Visit(E->getColumnIdx());
  1542. const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
  1543. unsigned NumRows = MatrixTy->getNumRows();
  1544. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  1545. Value *Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows);
  1546. if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
  1547. MB.CreateIndexAssumption(Idx, MatrixTy->getNumElementsFlattened());
  1548. Value *Matrix = Visit(E->getBase());
  1549. // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
  1550. return Builder.CreateExtractElement(Matrix, Idx, "matrixext");
  1551. }
  1552. static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
  1553. unsigned Off) {
  1554. int MV = SVI->getMaskValue(Idx);
  1555. if (MV == -1)
  1556. return -1;
  1557. return Off + MV;
  1558. }
  1559. static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
  1560. assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
  1561. "Index operand too large for shufflevector mask!");
  1562. return C->getZExtValue();
  1563. }
  1564. Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1565. bool Ignore = TestAndClearIgnoreResultAssign();
  1566. (void)Ignore;
  1567. assert (Ignore == false && "init list ignored");
  1568. unsigned NumInitElements = E->getNumInits();
  1569. if (E->hadArrayRangeDesignator())
  1570. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1571. llvm::VectorType *VType =
  1572. dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
  1573. if (!VType) {
  1574. if (NumInitElements == 0) {
  1575. // C++11 value-initialization for the scalar.
  1576. return EmitNullValue(E->getType());
  1577. }
  1578. // We have a scalar in braces. Just use the first element.
  1579. return Visit(E->getInit(0));
  1580. }
  1581. unsigned ResElts = cast<llvm::FixedVectorType>(VType)->getNumElements();
  1582. // Loop over initializers collecting the Value for each, and remembering
  1583. // whether the source was swizzle (ExtVectorElementExpr). This will allow
  1584. // us to fold the shuffle for the swizzle into the shuffle for the vector
  1585. // initializer, since LLVM optimizers generally do not want to touch
  1586. // shuffles.
  1587. unsigned CurIdx = 0;
  1588. bool VIsUndefShuffle = false;
  1589. llvm::Value *V = llvm::UndefValue::get(VType);
  1590. for (unsigned i = 0; i != NumInitElements; ++i) {
  1591. Expr *IE = E->getInit(i);
  1592. Value *Init = Visit(IE);
  1593. SmallVector<int, 16> Args;
  1594. llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
  1595. // Handle scalar elements. If the scalar initializer is actually one
  1596. // element of a different vector of the same width, use shuffle instead of
  1597. // extract+insert.
  1598. if (!VVT) {
  1599. if (isa<ExtVectorElementExpr>(IE)) {
  1600. llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
  1601. if (cast<llvm::FixedVectorType>(EI->getVectorOperandType())
  1602. ->getNumElements() == ResElts) {
  1603. llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
  1604. Value *LHS = nullptr, *RHS = nullptr;
  1605. if (CurIdx == 0) {
  1606. // insert into undef -> shuffle (src, undef)
  1607. // shufflemask must use an i32
  1608. Args.push_back(getAsInt32(C, CGF.Int32Ty));
  1609. Args.resize(ResElts, -1);
  1610. LHS = EI->getVectorOperand();
  1611. RHS = V;
  1612. VIsUndefShuffle = true;
  1613. } else if (VIsUndefShuffle) {
  1614. // insert into undefshuffle && size match -> shuffle (v, src)
  1615. llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
  1616. for (unsigned j = 0; j != CurIdx; ++j)
  1617. Args.push_back(getMaskElt(SVV, j, 0));
  1618. Args.push_back(ResElts + C->getZExtValue());
  1619. Args.resize(ResElts, -1);
  1620. LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1621. RHS = EI->getVectorOperand();
  1622. VIsUndefShuffle = false;
  1623. }
  1624. if (!Args.empty()) {
  1625. V = Builder.CreateShuffleVector(LHS, RHS, Args);
  1626. ++CurIdx;
  1627. continue;
  1628. }
  1629. }
  1630. }
  1631. V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
  1632. "vecinit");
  1633. VIsUndefShuffle = false;
  1634. ++CurIdx;
  1635. continue;
  1636. }
  1637. unsigned InitElts = cast<llvm::FixedVectorType>(VVT)->getNumElements();
  1638. // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
  1639. // input is the same width as the vector being constructed, generate an
  1640. // optimized shuffle of the swizzle input into the result.
  1641. unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
  1642. if (isa<ExtVectorElementExpr>(IE)) {
  1643. llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
  1644. Value *SVOp = SVI->getOperand(0);
  1645. auto *OpTy = cast<llvm::FixedVectorType>(SVOp->getType());
  1646. if (OpTy->getNumElements() == ResElts) {
  1647. for (unsigned j = 0; j != CurIdx; ++j) {
  1648. // If the current vector initializer is a shuffle with undef, merge
  1649. // this shuffle directly into it.
  1650. if (VIsUndefShuffle) {
  1651. Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0));
  1652. } else {
  1653. Args.push_back(j);
  1654. }
  1655. }
  1656. for (unsigned j = 0, je = InitElts; j != je; ++j)
  1657. Args.push_back(getMaskElt(SVI, j, Offset));
  1658. Args.resize(ResElts, -1);
  1659. if (VIsUndefShuffle)
  1660. V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
  1661. Init = SVOp;
  1662. }
  1663. }
  1664. // Extend init to result vector length, and then shuffle its contribution
  1665. // to the vector initializer into V.
  1666. if (Args.empty()) {
  1667. for (unsigned j = 0; j != InitElts; ++j)
  1668. Args.push_back(j);
  1669. Args.resize(ResElts, -1);
  1670. Init = Builder.CreateShuffleVector(Init, Args, "vext");
  1671. Args.clear();
  1672. for (unsigned j = 0; j != CurIdx; ++j)
  1673. Args.push_back(j);
  1674. for (unsigned j = 0; j != InitElts; ++j)
  1675. Args.push_back(j + Offset);
  1676. Args.resize(ResElts, -1);
  1677. }
  1678. // If V is undef, make sure it ends up on the RHS of the shuffle to aid
  1679. // merging subsequent shuffles into this one.
  1680. if (CurIdx == 0)
  1681. std::swap(V, Init);
  1682. V = Builder.CreateShuffleVector(V, Init, Args, "vecinit");
  1683. VIsUndefShuffle = isa<llvm::UndefValue>(Init);
  1684. CurIdx += InitElts;
  1685. }
  1686. // FIXME: evaluate codegen vs. shuffling against constant null vector.
  1687. // Emit remaining default initializers.
  1688. llvm::Type *EltTy = VType->getElementType();
  1689. // Emit remaining default initializers
  1690. for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
  1691. Value *Idx = Builder.getInt32(CurIdx);
  1692. llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
  1693. V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
  1694. }
  1695. return V;
  1696. }
  1697. bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
  1698. const Expr *E = CE->getSubExpr();
  1699. if (CE->getCastKind() == CK_UncheckedDerivedToBase)
  1700. return false;
  1701. if (isa<CXXThisExpr>(E->IgnoreParens())) {
  1702. // We always assume that 'this' is never null.
  1703. return false;
  1704. }
  1705. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  1706. // And that glvalue casts are never null.
  1707. if (ICE->isGLValue())
  1708. return false;
  1709. }
  1710. return true;
  1711. }
  1712. // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
  1713. // have to handle a more broad range of conversions than explicit casts, as they
  1714. // handle things like function to ptr-to-function decay etc.
  1715. Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
  1716. Expr *E = CE->getSubExpr();
  1717. QualType DestTy = CE->getType();
  1718. CastKind Kind = CE->getCastKind();
  1719. // These cases are generally not written to ignore the result of
  1720. // evaluating their sub-expressions, so we clear this now.
  1721. bool Ignored = TestAndClearIgnoreResultAssign();
  1722. // Since almost all cast kinds apply to scalars, this switch doesn't have
  1723. // a default case, so the compiler will warn on a missing case. The cases
  1724. // are in the same order as in the CastKind enum.
  1725. switch (Kind) {
  1726. case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
  1727. case CK_BuiltinFnToFnPtr:
  1728. llvm_unreachable("builtin functions are handled elsewhere");
  1729. case CK_LValueBitCast:
  1730. case CK_ObjCObjectLValueCast: {
  1731. Address Addr = EmitLValue(E).getAddress(CGF);
  1732. Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
  1733. LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
  1734. return EmitLoadOfLValue(LV, CE->getExprLoc());
  1735. }
  1736. case CK_LValueToRValueBitCast: {
  1737. LValue SourceLVal = CGF.EmitLValue(E);
  1738. Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
  1739. CGF.ConvertTypeForMem(DestTy));
  1740. LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
  1741. DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
  1742. return EmitLoadOfLValue(DestLV, CE->getExprLoc());
  1743. }
  1744. case CK_CPointerToObjCPointerCast:
  1745. case CK_BlockPointerToObjCPointerCast:
  1746. case CK_AnyPointerToBlockPointerCast:
  1747. case CK_BitCast: {
  1748. Value *Src = Visit(const_cast<Expr*>(E));
  1749. llvm::Type *SrcTy = Src->getType();
  1750. llvm::Type *DstTy = ConvertType(DestTy);
  1751. if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
  1752. SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
  1753. llvm_unreachable("wrong cast for pointers in different address spaces"
  1754. "(must be an address space cast)!");
  1755. }
  1756. if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  1757. if (auto PT = DestTy->getAs<PointerType>())
  1758. CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
  1759. /*MayBeNull=*/true,
  1760. CodeGenFunction::CFITCK_UnrelatedCast,
  1761. CE->getBeginLoc());
  1762. }
  1763. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1764. const QualType SrcType = E->getType();
  1765. if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
  1766. // Casting to pointer that could carry dynamic information (provided by
  1767. // invariant.group) requires launder.
  1768. Src = Builder.CreateLaunderInvariantGroup(Src);
  1769. } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
  1770. // Casting to pointer that does not carry dynamic information (provided
  1771. // by invariant.group) requires stripping it. Note that we don't do it
  1772. // if the source could not be dynamic type and destination could be
  1773. // dynamic because dynamic information is already laundered. It is
  1774. // because launder(strip(src)) == launder(src), so there is no need to
  1775. // add extra strip before launder.
  1776. Src = Builder.CreateStripInvariantGroup(Src);
  1777. }
  1778. }
  1779. // Update heapallocsite metadata when there is an explicit pointer cast.
  1780. if (auto *CI = dyn_cast<llvm::CallBase>(Src)) {
  1781. if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE)) {
  1782. QualType PointeeType = DestTy->getPointeeType();
  1783. if (!PointeeType.isNull())
  1784. CGF.getDebugInfo()->addHeapAllocSiteMetadata(CI, PointeeType,
  1785. CE->getExprLoc());
  1786. }
  1787. }
  1788. // If Src is a fixed vector and Dst is a scalable vector, and both have the
  1789. // same element type, use the llvm.experimental.vector.insert intrinsic to
  1790. // perform the bitcast.
  1791. if (const auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
  1792. if (const auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(DstTy)) {
  1793. // If we are casting a fixed i8 vector to a scalable 16 x i1 predicate
  1794. // vector, use a vector insert and bitcast the result.
  1795. bool NeedsBitCast = false;
  1796. auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
  1797. llvm::Type *OrigType = DstTy;
  1798. if (ScalableDst == PredType &&
  1799. FixedSrc->getElementType() == Builder.getInt8Ty()) {
  1800. DstTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
  1801. ScalableDst = dyn_cast<llvm::ScalableVectorType>(DstTy);
  1802. NeedsBitCast = true;
  1803. }
  1804. if (FixedSrc->getElementType() == ScalableDst->getElementType()) {
  1805. llvm::Value *UndefVec = llvm::UndefValue::get(DstTy);
  1806. llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
  1807. llvm::Value *Result = Builder.CreateInsertVector(
  1808. DstTy, UndefVec, Src, Zero, "castScalableSve");
  1809. if (NeedsBitCast)
  1810. Result = Builder.CreateBitCast(Result, OrigType);
  1811. return Result;
  1812. }
  1813. }
  1814. }
  1815. // If Src is a scalable vector and Dst is a fixed vector, and both have the
  1816. // same element type, use the llvm.experimental.vector.extract intrinsic to
  1817. // perform the bitcast.
  1818. if (const auto *ScalableSrc = dyn_cast<llvm::ScalableVectorType>(SrcTy)) {
  1819. if (const auto *FixedDst = dyn_cast<llvm::FixedVectorType>(DstTy)) {
  1820. // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
  1821. // vector, bitcast the source and use a vector extract.
  1822. auto PredType = llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
  1823. if (ScalableSrc == PredType &&
  1824. FixedDst->getElementType() == Builder.getInt8Ty()) {
  1825. SrcTy = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
  1826. ScalableSrc = dyn_cast<llvm::ScalableVectorType>(SrcTy);
  1827. Src = Builder.CreateBitCast(Src, SrcTy);
  1828. }
  1829. if (ScalableSrc->getElementType() == FixedDst->getElementType()) {
  1830. llvm::Value *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
  1831. return Builder.CreateExtractVector(DstTy, Src, Zero, "castFixedSve");
  1832. }
  1833. }
  1834. }
  1835. // Perform VLAT <-> VLST bitcast through memory.
  1836. // TODO: since the llvm.experimental.vector.{insert,extract} intrinsics
  1837. // require the element types of the vectors to be the same, we
  1838. // need to keep this around for bitcasts between VLAT <-> VLST where
  1839. // the element types of the vectors are not the same, until we figure
  1840. // out a better way of doing these casts.
  1841. if ((isa<llvm::FixedVectorType>(SrcTy) &&
  1842. isa<llvm::ScalableVectorType>(DstTy)) ||
  1843. (isa<llvm::ScalableVectorType>(SrcTy) &&
  1844. isa<llvm::FixedVectorType>(DstTy))) {
  1845. Address Addr = CGF.CreateDefaultAlignTempAlloca(SrcTy, "saved-value");
  1846. LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
  1847. CGF.EmitStoreOfScalar(Src, LV);
  1848. Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy),
  1849. "castFixedSve");
  1850. LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
  1851. DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
  1852. return EmitLoadOfLValue(DestLV, CE->getExprLoc());
  1853. }
  1854. return Builder.CreateBitCast(Src, DstTy);
  1855. }
  1856. case CK_AddressSpaceConversion: {
  1857. Expr::EvalResult Result;
  1858. if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
  1859. Result.Val.isNullPointer()) {
  1860. // If E has side effect, it is emitted even if its final result is a
  1861. // null pointer. In that case, a DCE pass should be able to
  1862. // eliminate the useless instructions emitted during translating E.
  1863. if (Result.HasSideEffects)
  1864. Visit(E);
  1865. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
  1866. ConvertType(DestTy)), DestTy);
  1867. }
  1868. // Since target may map different address spaces in AST to the same address
  1869. // space, an address space conversion may end up as a bitcast.
  1870. return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  1871. CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
  1872. DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
  1873. }
  1874. case CK_AtomicToNonAtomic:
  1875. case CK_NonAtomicToAtomic:
  1876. case CK_UserDefinedConversion:
  1877. return Visit(const_cast<Expr*>(E));
  1878. case CK_NoOp: {
  1879. llvm::Value *V = Visit(const_cast<Expr *>(E));
  1880. if (V) {
  1881. // CK_NoOp can model a pointer qualification conversion, which can remove
  1882. // an array bound and change the IR type.
  1883. // FIXME: Once pointee types are removed from IR, remove this.
  1884. llvm::Type *T = ConvertType(DestTy);
  1885. if (T != V->getType())
  1886. V = Builder.CreateBitCast(V, T);
  1887. }
  1888. return V;
  1889. }
  1890. case CK_BaseToDerived: {
  1891. const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
  1892. assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
  1893. Address Base = CGF.EmitPointerWithAlignment(E);
  1894. Address Derived =
  1895. CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
  1896. CE->path_begin(), CE->path_end(),
  1897. CGF.ShouldNullCheckClassCastValue(CE));
  1898. // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
  1899. // performed and the object is not of the derived type.
  1900. if (CGF.sanitizePerformTypeCheck())
  1901. CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
  1902. Derived.getPointer(), DestTy->getPointeeType());
  1903. if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
  1904. CGF.EmitVTablePtrCheckForCast(
  1905. DestTy->getPointeeType(), Derived.getPointer(),
  1906. /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
  1907. CE->getBeginLoc());
  1908. return Derived.getPointer();
  1909. }
  1910. case CK_UncheckedDerivedToBase:
  1911. case CK_DerivedToBase: {
  1912. // The EmitPointerWithAlignment path does this fine; just discard
  1913. // the alignment.
  1914. return CGF.EmitPointerWithAlignment(CE).getPointer();
  1915. }
  1916. case CK_Dynamic: {
  1917. Address V = CGF.EmitPointerWithAlignment(E);
  1918. const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
  1919. return CGF.EmitDynamicCast(V, DCE);
  1920. }
  1921. case CK_ArrayToPointerDecay:
  1922. return CGF.EmitArrayToPointerDecay(E).getPointer();
  1923. case CK_FunctionToPointerDecay:
  1924. return EmitLValue(E).getPointer(CGF);
  1925. case CK_NullToPointer:
  1926. if (MustVisitNullValue(E))
  1927. CGF.EmitIgnoredExpr(E);
  1928. return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
  1929. DestTy);
  1930. case CK_NullToMemberPointer: {
  1931. if (MustVisitNullValue(E))
  1932. CGF.EmitIgnoredExpr(E);
  1933. const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
  1934. return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1935. }
  1936. case CK_ReinterpretMemberPointer:
  1937. case CK_BaseToDerivedMemberPointer:
  1938. case CK_DerivedToBaseMemberPointer: {
  1939. Value *Src = Visit(E);
  1940. // Note that the AST doesn't distinguish between checked and
  1941. // unchecked member pointer conversions, so we always have to
  1942. // implement checked conversions here. This is inefficient when
  1943. // actual control flow may be required in order to perform the
  1944. // check, which it is for data member pointers (but not member
  1945. // function pointers on Itanium and ARM).
  1946. return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
  1947. }
  1948. case CK_ARCProduceObject:
  1949. return CGF.EmitARCRetainScalarExpr(E);
  1950. case CK_ARCConsumeObject:
  1951. return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
  1952. case CK_ARCReclaimReturnedObject:
  1953. return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
  1954. case CK_ARCExtendBlockObject:
  1955. return CGF.EmitARCExtendBlockObject(E);
  1956. case CK_CopyAndAutoreleaseBlockObject:
  1957. return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
  1958. case CK_FloatingRealToComplex:
  1959. case CK_FloatingComplexCast:
  1960. case CK_IntegralRealToComplex:
  1961. case CK_IntegralComplexCast:
  1962. case CK_IntegralComplexToFloatingComplex:
  1963. case CK_FloatingComplexToIntegralComplex:
  1964. case CK_ConstructorConversion:
  1965. case CK_ToUnion:
  1966. llvm_unreachable("scalar cast to non-scalar value");
  1967. case CK_LValueToRValue:
  1968. assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
  1969. assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
  1970. return Visit(const_cast<Expr*>(E));
  1971. case CK_IntegralToPointer: {
  1972. Value *Src = Visit(const_cast<Expr*>(E));
  1973. // First, convert to the correct width so that we control the kind of
  1974. // extension.
  1975. auto DestLLVMTy = ConvertType(DestTy);
  1976. llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
  1977. bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
  1978. llvm::Value* IntResult =
  1979. Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
  1980. auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
  1981. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1982. // Going from integer to pointer that could be dynamic requires reloading
  1983. // dynamic information from invariant.group.
  1984. if (DestTy.mayBeDynamicClass())
  1985. IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
  1986. }
  1987. return IntToPtr;
  1988. }
  1989. case CK_PointerToIntegral: {
  1990. assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
  1991. auto *PtrExpr = Visit(E);
  1992. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
  1993. const QualType SrcType = E->getType();
  1994. // Casting to integer requires stripping dynamic information as it does
  1995. // not carries it.
  1996. if (SrcType.mayBeDynamicClass())
  1997. PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
  1998. }
  1999. return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
  2000. }
  2001. case CK_ToVoid: {
  2002. CGF.EmitIgnoredExpr(E);
  2003. return nullptr;
  2004. }
  2005. case CK_MatrixCast: {
  2006. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2007. CE->getExprLoc());
  2008. }
  2009. case CK_VectorSplat: {
  2010. llvm::Type *DstTy = ConvertType(DestTy);
  2011. Value *Elt = Visit(const_cast<Expr*>(E));
  2012. // Splat the element across to all elements
  2013. unsigned NumElements = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
  2014. return Builder.CreateVectorSplat(NumElements, Elt, "splat");
  2015. }
  2016. case CK_FixedPointCast:
  2017. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2018. CE->getExprLoc());
  2019. case CK_FixedPointToBoolean:
  2020. assert(E->getType()->isFixedPointType() &&
  2021. "Expected src type to be fixed point type");
  2022. assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
  2023. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2024. CE->getExprLoc());
  2025. case CK_FixedPointToIntegral:
  2026. assert(E->getType()->isFixedPointType() &&
  2027. "Expected src type to be fixed point type");
  2028. assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
  2029. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2030. CE->getExprLoc());
  2031. case CK_IntegralToFixedPoint:
  2032. assert(E->getType()->isIntegerType() &&
  2033. "Expected src type to be an integer");
  2034. assert(DestTy->isFixedPointType() &&
  2035. "Expected dest type to be fixed point type");
  2036. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2037. CE->getExprLoc());
  2038. case CK_IntegralCast: {
  2039. ScalarConversionOpts Opts;
  2040. if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
  2041. if (!ICE->isPartOfExplicitCast())
  2042. Opts = ScalarConversionOpts(CGF.SanOpts);
  2043. }
  2044. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2045. CE->getExprLoc(), Opts);
  2046. }
  2047. case CK_IntegralToFloating:
  2048. case CK_FloatingToIntegral:
  2049. case CK_FloatingCast:
  2050. case CK_FixedPointToFloating:
  2051. case CK_FloatingToFixedPoint: {
  2052. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
  2053. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2054. CE->getExprLoc());
  2055. }
  2056. case CK_BooleanToSignedIntegral: {
  2057. ScalarConversionOpts Opts;
  2058. Opts.TreatBooleanAsSigned = true;
  2059. return EmitScalarConversion(Visit(E), E->getType(), DestTy,
  2060. CE->getExprLoc(), Opts);
  2061. }
  2062. case CK_IntegralToBoolean:
  2063. return EmitIntToBoolConversion(Visit(E));
  2064. case CK_PointerToBoolean:
  2065. return EmitPointerToBoolConversion(Visit(E), E->getType());
  2066. case CK_FloatingToBoolean: {
  2067. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
  2068. return EmitFloatToBoolConversion(Visit(E));
  2069. }
  2070. case CK_MemberPointerToBoolean: {
  2071. llvm::Value *MemPtr = Visit(E);
  2072. const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
  2073. return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
  2074. }
  2075. case CK_FloatingComplexToReal:
  2076. case CK_IntegralComplexToReal:
  2077. return CGF.EmitComplexExpr(E, false, true).first;
  2078. case CK_FloatingComplexToBoolean:
  2079. case CK_IntegralComplexToBoolean: {
  2080. CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
  2081. // TODO: kill this function off, inline appropriate case here
  2082. return EmitComplexToScalarConversion(V, E->getType(), DestTy,
  2083. CE->getExprLoc());
  2084. }
  2085. case CK_ZeroToOCLOpaqueType: {
  2086. assert((DestTy->isEventT() || DestTy->isQueueT() ||
  2087. DestTy->isOCLIntelSubgroupAVCType()) &&
  2088. "CK_ZeroToOCLEvent cast on non-event type");
  2089. return llvm::Constant::getNullValue(ConvertType(DestTy));
  2090. }
  2091. case CK_IntToOCLSampler:
  2092. return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
  2093. } // end of switch
  2094. llvm_unreachable("unknown scalar cast");
  2095. }
  2096. Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  2097. CodeGenFunction::StmtExprEvaluation eval(CGF);
  2098. Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
  2099. !E->getType()->isVoidType());
  2100. if (!RetAlloca.isValid())
  2101. return nullptr;
  2102. return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
  2103. E->getExprLoc());
  2104. }
  2105. Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  2106. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2107. Value *V = Visit(E->getSubExpr());
  2108. // Defend against dominance problems caused by jumps out of expression
  2109. // evaluation through the shared cleanup block.
  2110. Scope.ForceCleanup({&V});
  2111. return V;
  2112. }
  2113. //===----------------------------------------------------------------------===//
  2114. // Unary Operators
  2115. //===----------------------------------------------------------------------===//
  2116. static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
  2117. llvm::Value *InVal, bool IsInc,
  2118. FPOptions FPFeatures) {
  2119. BinOpInfo BinOp;
  2120. BinOp.LHS = InVal;
  2121. BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
  2122. BinOp.Ty = E->getType();
  2123. BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
  2124. BinOp.FPFeatures = FPFeatures;
  2125. BinOp.E = E;
  2126. return BinOp;
  2127. }
  2128. llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
  2129. const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
  2130. llvm::Value *Amount =
  2131. llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
  2132. StringRef Name = IsInc ? "inc" : "dec";
  2133. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  2134. case LangOptions::SOB_Defined:
  2135. return Builder.CreateAdd(InVal, Amount, Name);
  2136. case LangOptions::SOB_Undefined:
  2137. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  2138. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2139. LLVM_FALLTHROUGH;
  2140. case LangOptions::SOB_Trapping:
  2141. if (!E->canOverflow())
  2142. return Builder.CreateNSWAdd(InVal, Amount, Name);
  2143. return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
  2144. E, InVal, IsInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
  2145. }
  2146. llvm_unreachable("Unknown SignedOverflowBehaviorTy");
  2147. }
  2148. namespace {
  2149. /// Handles check and update for lastprivate conditional variables.
  2150. class OMPLastprivateConditionalUpdateRAII {
  2151. private:
  2152. CodeGenFunction &CGF;
  2153. const UnaryOperator *E;
  2154. public:
  2155. OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
  2156. const UnaryOperator *E)
  2157. : CGF(CGF), E(E) {}
  2158. ~OMPLastprivateConditionalUpdateRAII() {
  2159. if (CGF.getLangOpts().OpenMP)
  2160. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
  2161. CGF, E->getSubExpr());
  2162. }
  2163. };
  2164. } // namespace
  2165. llvm::Value *
  2166. ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2167. bool isInc, bool isPre) {
  2168. OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
  2169. QualType type = E->getSubExpr()->getType();
  2170. llvm::PHINode *atomicPHI = nullptr;
  2171. llvm::Value *value;
  2172. llvm::Value *input;
  2173. int amount = (isInc ? 1 : -1);
  2174. bool isSubtraction = !isInc;
  2175. if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
  2176. type = atomicTy->getValueType();
  2177. if (isInc && type->isBooleanType()) {
  2178. llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
  2179. if (isPre) {
  2180. Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
  2181. ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
  2182. return Builder.getTrue();
  2183. }
  2184. // For atomic bool increment, we just store true and return it for
  2185. // preincrement, do an atomic swap with true for postincrement
  2186. return Builder.CreateAtomicRMW(
  2187. llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
  2188. llvm::AtomicOrdering::SequentiallyConsistent);
  2189. }
  2190. // Special case for atomic increment / decrement on integers, emit
  2191. // atomicrmw instructions. We skip this if we want to be doing overflow
  2192. // checking, and fall into the slow path with the atomic cmpxchg loop.
  2193. if (!type->isBooleanType() && type->isIntegerType() &&
  2194. !(type->isUnsignedIntegerType() &&
  2195. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2196. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2197. LangOptions::SOB_Trapping) {
  2198. llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
  2199. llvm::AtomicRMWInst::Sub;
  2200. llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
  2201. llvm::Instruction::Sub;
  2202. llvm::Value *amt = CGF.EmitToMemory(
  2203. llvm::ConstantInt::get(ConvertType(type), 1, true), type);
  2204. llvm::Value *old =
  2205. Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
  2206. llvm::AtomicOrdering::SequentiallyConsistent);
  2207. return isPre ? Builder.CreateBinOp(op, old, amt) : old;
  2208. }
  2209. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2210. input = value;
  2211. // For every other atomic operation, we need to emit a load-op-cmpxchg loop
  2212. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2213. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2214. value = CGF.EmitToMemory(value, type);
  2215. Builder.CreateBr(opBB);
  2216. Builder.SetInsertPoint(opBB);
  2217. atomicPHI = Builder.CreatePHI(value->getType(), 2);
  2218. atomicPHI->addIncoming(value, startBB);
  2219. value = atomicPHI;
  2220. } else {
  2221. value = EmitLoadOfLValue(LV, E->getExprLoc());
  2222. input = value;
  2223. }
  2224. // Special case of integer increment that we have to check first: bool++.
  2225. // Due to promotion rules, we get:
  2226. // bool++ -> bool = bool + 1
  2227. // -> bool = (int)bool + 1
  2228. // -> bool = ((int)bool + 1 != 0)
  2229. // An interesting aspect of this is that increment is always true.
  2230. // Decrement does not have this property.
  2231. if (isInc && type->isBooleanType()) {
  2232. value = Builder.getTrue();
  2233. // Most common case by far: integer increment.
  2234. } else if (type->isIntegerType()) {
  2235. QualType promotedType;
  2236. bool canPerformLossyDemotionCheck = false;
  2237. if (type->isPromotableIntegerType()) {
  2238. promotedType = CGF.getContext().getPromotedIntegerType(type);
  2239. assert(promotedType != type && "Shouldn't promote to the same type.");
  2240. canPerformLossyDemotionCheck = true;
  2241. canPerformLossyDemotionCheck &=
  2242. CGF.getContext().getCanonicalType(type) !=
  2243. CGF.getContext().getCanonicalType(promotedType);
  2244. canPerformLossyDemotionCheck &=
  2245. PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
  2246. type, promotedType);
  2247. assert((!canPerformLossyDemotionCheck ||
  2248. type->isSignedIntegerOrEnumerationType() ||
  2249. promotedType->isSignedIntegerOrEnumerationType() ||
  2250. ConvertType(type)->getScalarSizeInBits() ==
  2251. ConvertType(promotedType)->getScalarSizeInBits()) &&
  2252. "The following check expects that if we do promotion to different "
  2253. "underlying canonical type, at least one of the types (either "
  2254. "base or promoted) will be signed, or the bitwidths will match.");
  2255. }
  2256. if (CGF.SanOpts.hasOneOf(
  2257. SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
  2258. canPerformLossyDemotionCheck) {
  2259. // While `x += 1` (for `x` with width less than int) is modeled as
  2260. // promotion+arithmetics+demotion, and we can catch lossy demotion with
  2261. // ease; inc/dec with width less than int can't overflow because of
  2262. // promotion rules, so we omit promotion+demotion, which means that we can
  2263. // not catch lossy "demotion". Because we still want to catch these cases
  2264. // when the sanitizer is enabled, we perform the promotion, then perform
  2265. // the increment/decrement in the wider type, and finally
  2266. // perform the demotion. This will catch lossy demotions.
  2267. value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
  2268. Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
  2269. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2270. // Do pass non-default ScalarConversionOpts so that sanitizer check is
  2271. // emitted.
  2272. value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
  2273. ScalarConversionOpts(CGF.SanOpts));
  2274. // Note that signed integer inc/dec with width less than int can't
  2275. // overflow because of promotion rules; we're just eliding a few steps
  2276. // here.
  2277. } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
  2278. value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
  2279. } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
  2280. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
  2281. value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
  2282. E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
  2283. } else {
  2284. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
  2285. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2286. }
  2287. // Next most common: pointer increment.
  2288. } else if (const PointerType *ptr = type->getAs<PointerType>()) {
  2289. QualType type = ptr->getPointeeType();
  2290. // VLA types don't have constant size.
  2291. if (const VariableArrayType *vla
  2292. = CGF.getContext().getAsVariableArrayType(type)) {
  2293. llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
  2294. if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
  2295. llvm::Type *elemTy = value->getType()->getPointerElementType();
  2296. if (CGF.getLangOpts().isSignedOverflowDefined())
  2297. value = Builder.CreateGEP(elemTy, value, numElts, "vla.inc");
  2298. else
  2299. value = CGF.EmitCheckedInBoundsGEP(
  2300. elemTy, value, numElts, /*SignedIndices=*/false, isSubtraction,
  2301. E->getExprLoc(), "vla.inc");
  2302. // Arithmetic on function pointers (!) is just +-1.
  2303. } else if (type->isFunctionType()) {
  2304. llvm::Value *amt = Builder.getInt32(amount);
  2305. value = CGF.EmitCastToVoidPtr(value);
  2306. if (CGF.getLangOpts().isSignedOverflowDefined())
  2307. value = Builder.CreateGEP(CGF.Int8Ty, value, amt, "incdec.funcptr");
  2308. else
  2309. value = CGF.EmitCheckedInBoundsGEP(CGF.Int8Ty, value, amt,
  2310. /*SignedIndices=*/false,
  2311. isSubtraction, E->getExprLoc(),
  2312. "incdec.funcptr");
  2313. value = Builder.CreateBitCast(value, input->getType());
  2314. // For everything else, we can just do a simple increment.
  2315. } else {
  2316. llvm::Value *amt = Builder.getInt32(amount);
  2317. llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
  2318. if (CGF.getLangOpts().isSignedOverflowDefined())
  2319. value = Builder.CreateGEP(elemTy, value, amt, "incdec.ptr");
  2320. else
  2321. value = CGF.EmitCheckedInBoundsGEP(
  2322. elemTy, value, amt, /*SignedIndices=*/false, isSubtraction,
  2323. E->getExprLoc(), "incdec.ptr");
  2324. }
  2325. // Vector increment/decrement.
  2326. } else if (type->isVectorType()) {
  2327. if (type->hasIntegerRepresentation()) {
  2328. llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
  2329. value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
  2330. } else {
  2331. value = Builder.CreateFAdd(
  2332. value,
  2333. llvm::ConstantFP::get(value->getType(), amount),
  2334. isInc ? "inc" : "dec");
  2335. }
  2336. // Floating point.
  2337. } else if (type->isRealFloatingType()) {
  2338. // Add the inc/dec to the real part.
  2339. llvm::Value *amt;
  2340. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
  2341. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2342. // Another special case: half FP increment should be done via float
  2343. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2344. value = Builder.CreateCall(
  2345. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
  2346. CGF.CGM.FloatTy),
  2347. input, "incdec.conv");
  2348. } else {
  2349. value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
  2350. }
  2351. }
  2352. if (value->getType()->isFloatTy())
  2353. amt = llvm::ConstantFP::get(VMContext,
  2354. llvm::APFloat(static_cast<float>(amount)));
  2355. else if (value->getType()->isDoubleTy())
  2356. amt = llvm::ConstantFP::get(VMContext,
  2357. llvm::APFloat(static_cast<double>(amount)));
  2358. else {
  2359. // Remaining types are Half, LongDouble, __ibm128 or __float128. Convert
  2360. // from float.
  2361. llvm::APFloat F(static_cast<float>(amount));
  2362. bool ignored;
  2363. const llvm::fltSemantics *FS;
  2364. // Don't use getFloatTypeSemantics because Half isn't
  2365. // necessarily represented using the "half" LLVM type.
  2366. if (value->getType()->isFP128Ty())
  2367. FS = &CGF.getTarget().getFloat128Format();
  2368. else if (value->getType()->isHalfTy())
  2369. FS = &CGF.getTarget().getHalfFormat();
  2370. else if (value->getType()->isPPC_FP128Ty())
  2371. FS = &CGF.getTarget().getIbm128Format();
  2372. else
  2373. FS = &CGF.getTarget().getLongDoubleFormat();
  2374. F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
  2375. amt = llvm::ConstantFP::get(VMContext, F);
  2376. }
  2377. value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
  2378. if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
  2379. if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
  2380. value = Builder.CreateCall(
  2381. CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
  2382. CGF.CGM.FloatTy),
  2383. value, "incdec.conv");
  2384. } else {
  2385. value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
  2386. }
  2387. }
  2388. // Fixed-point types.
  2389. } else if (type->isFixedPointType()) {
  2390. // Fixed-point types are tricky. In some cases, it isn't possible to
  2391. // represent a 1 or a -1 in the type at all. Piggyback off of
  2392. // EmitFixedPointBinOp to avoid having to reimplement saturation.
  2393. BinOpInfo Info;
  2394. Info.E = E;
  2395. Info.Ty = E->getType();
  2396. Info.Opcode = isInc ? BO_Add : BO_Sub;
  2397. Info.LHS = value;
  2398. Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
  2399. // If the type is signed, it's better to represent this as +(-1) or -(-1),
  2400. // since -1 is guaranteed to be representable.
  2401. if (type->isSignedFixedPointType()) {
  2402. Info.Opcode = isInc ? BO_Sub : BO_Add;
  2403. Info.RHS = Builder.CreateNeg(Info.RHS);
  2404. }
  2405. // Now, convert from our invented integer literal to the type of the unary
  2406. // op. This will upscale and saturate if necessary. This value can become
  2407. // undef in some cases.
  2408. llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
  2409. auto DstSema = CGF.getContext().getFixedPointSemantics(Info.Ty);
  2410. Info.RHS = FPBuilder.CreateIntegerToFixed(Info.RHS, true, DstSema);
  2411. value = EmitFixedPointBinOp(Info);
  2412. // Objective-C pointer types.
  2413. } else {
  2414. const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
  2415. value = CGF.EmitCastToVoidPtr(value);
  2416. CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
  2417. if (!isInc) size = -size;
  2418. llvm::Value *sizeValue =
  2419. llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
  2420. if (CGF.getLangOpts().isSignedOverflowDefined())
  2421. value = Builder.CreateGEP(CGF.Int8Ty, value, sizeValue, "incdec.objptr");
  2422. else
  2423. value = CGF.EmitCheckedInBoundsGEP(
  2424. CGF.Int8Ty, value, sizeValue, /*SignedIndices=*/false, isSubtraction,
  2425. E->getExprLoc(), "incdec.objptr");
  2426. value = Builder.CreateBitCast(value, input->getType());
  2427. }
  2428. if (atomicPHI) {
  2429. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2430. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2431. auto Pair = CGF.EmitAtomicCompareExchange(
  2432. LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
  2433. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
  2434. llvm::Value *success = Pair.second;
  2435. atomicPHI->addIncoming(old, curBlock);
  2436. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2437. Builder.SetInsertPoint(contBB);
  2438. return isPre ? value : input;
  2439. }
  2440. // Store the updated result through the lvalue.
  2441. if (LV.isBitField())
  2442. CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
  2443. else
  2444. CGF.EmitStoreThroughLValue(RValue::get(value), LV);
  2445. // If this is a postinc, return the value read from memory, otherwise use the
  2446. // updated value.
  2447. return isPre ? value : input;
  2448. }
  2449. Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
  2450. TestAndClearIgnoreResultAssign();
  2451. Value *Op = Visit(E->getSubExpr());
  2452. // Generate a unary FNeg for FP ops.
  2453. if (Op->getType()->isFPOrFPVectorTy())
  2454. return Builder.CreateFNeg(Op, "fneg");
  2455. // Emit unary minus with EmitSub so we handle overflow cases etc.
  2456. BinOpInfo BinOp;
  2457. BinOp.RHS = Op;
  2458. BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
  2459. BinOp.Ty = E->getType();
  2460. BinOp.Opcode = BO_Sub;
  2461. BinOp.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
  2462. BinOp.E = E;
  2463. return EmitSub(BinOp);
  2464. }
  2465. Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
  2466. TestAndClearIgnoreResultAssign();
  2467. Value *Op = Visit(E->getSubExpr());
  2468. return Builder.CreateNot(Op, "neg");
  2469. }
  2470. Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
  2471. // Perform vector logical not on comparison with zero vector.
  2472. if (E->getType()->isVectorType() &&
  2473. E->getType()->castAs<VectorType>()->getVectorKind() ==
  2474. VectorType::GenericVector) {
  2475. Value *Oper = Visit(E->getSubExpr());
  2476. Value *Zero = llvm::Constant::getNullValue(Oper->getType());
  2477. Value *Result;
  2478. if (Oper->getType()->isFPOrFPVectorTy()) {
  2479. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
  2480. CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
  2481. Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
  2482. } else
  2483. Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
  2484. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  2485. }
  2486. // Compare operand to zero.
  2487. Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
  2488. // Invert value.
  2489. // TODO: Could dynamically modify easy computations here. For example, if
  2490. // the operand is an icmp ne, turn into icmp eq.
  2491. BoolVal = Builder.CreateNot(BoolVal, "lnot");
  2492. // ZExt result to the expr type.
  2493. return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
  2494. }
  2495. Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
  2496. // Try folding the offsetof to a constant.
  2497. Expr::EvalResult EVResult;
  2498. if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
  2499. llvm::APSInt Value = EVResult.Val.getInt();
  2500. return Builder.getInt(Value);
  2501. }
  2502. // Loop over the components of the offsetof to compute the value.
  2503. unsigned n = E->getNumComponents();
  2504. llvm::Type* ResultType = ConvertType(E->getType());
  2505. llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
  2506. QualType CurrentType = E->getTypeSourceInfo()->getType();
  2507. for (unsigned i = 0; i != n; ++i) {
  2508. OffsetOfNode ON = E->getComponent(i);
  2509. llvm::Value *Offset = nullptr;
  2510. switch (ON.getKind()) {
  2511. case OffsetOfNode::Array: {
  2512. // Compute the index
  2513. Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
  2514. llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
  2515. bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
  2516. Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
  2517. // Save the element type
  2518. CurrentType =
  2519. CGF.getContext().getAsArrayType(CurrentType)->getElementType();
  2520. // Compute the element size
  2521. llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
  2522. CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
  2523. // Multiply out to compute the result
  2524. Offset = Builder.CreateMul(Idx, ElemSize);
  2525. break;
  2526. }
  2527. case OffsetOfNode::Field: {
  2528. FieldDecl *MemberDecl = ON.getField();
  2529. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2530. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2531. // Compute the index of the field in its parent.
  2532. unsigned i = 0;
  2533. // FIXME: It would be nice if we didn't have to loop here!
  2534. for (RecordDecl::field_iterator Field = RD->field_begin(),
  2535. FieldEnd = RD->field_end();
  2536. Field != FieldEnd; ++Field, ++i) {
  2537. if (*Field == MemberDecl)
  2538. break;
  2539. }
  2540. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  2541. // Compute the offset to the field
  2542. int64_t OffsetInt = RL.getFieldOffset(i) /
  2543. CGF.getContext().getCharWidth();
  2544. Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
  2545. // Save the element type.
  2546. CurrentType = MemberDecl->getType();
  2547. break;
  2548. }
  2549. case OffsetOfNode::Identifier:
  2550. llvm_unreachable("dependent __builtin_offsetof");
  2551. case OffsetOfNode::Base: {
  2552. if (ON.getBase()->isVirtual()) {
  2553. CGF.ErrorUnsupported(E, "virtual base in offsetof");
  2554. continue;
  2555. }
  2556. RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
  2557. const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
  2558. // Save the element type.
  2559. CurrentType = ON.getBase()->getType();
  2560. // Compute the offset to the base.
  2561. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  2562. CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
  2563. CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
  2564. Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
  2565. break;
  2566. }
  2567. }
  2568. Result = Builder.CreateAdd(Result, Offset);
  2569. }
  2570. return Result;
  2571. }
  2572. /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
  2573. /// argument of the sizeof expression as an integer.
  2574. Value *
  2575. ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
  2576. const UnaryExprOrTypeTraitExpr *E) {
  2577. QualType TypeToSize = E->getTypeOfArgument();
  2578. if (E->getKind() == UETT_SizeOf) {
  2579. if (const VariableArrayType *VAT =
  2580. CGF.getContext().getAsVariableArrayType(TypeToSize)) {
  2581. if (E->isArgumentType()) {
  2582. // sizeof(type) - make sure to emit the VLA size.
  2583. CGF.EmitVariablyModifiedType(TypeToSize);
  2584. } else {
  2585. // C99 6.5.3.4p2: If the argument is an expression of type
  2586. // VLA, it is evaluated.
  2587. CGF.EmitIgnoredExpr(E->getArgumentExpr());
  2588. }
  2589. auto VlaSize = CGF.getVLASize(VAT);
  2590. llvm::Value *size = VlaSize.NumElts;
  2591. // Scale the number of non-VLA elements by the non-VLA element size.
  2592. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
  2593. if (!eltSize.isOne())
  2594. size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
  2595. return size;
  2596. }
  2597. } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
  2598. auto Alignment =
  2599. CGF.getContext()
  2600. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  2601. E->getTypeOfArgument()->getPointeeType()))
  2602. .getQuantity();
  2603. return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
  2604. }
  2605. // If this isn't sizeof(vla), the result must be constant; use the constant
  2606. // folding logic so we don't have to duplicate it here.
  2607. return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
  2608. }
  2609. Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
  2610. Expr *Op = E->getSubExpr();
  2611. if (Op->getType()->isAnyComplexType()) {
  2612. // If it's an l-value, load through the appropriate subobject l-value.
  2613. // Note that we have to ask E because Op might be an l-value that
  2614. // this won't work for, e.g. an Obj-C property.
  2615. if (E->isGLValue())
  2616. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2617. E->getExprLoc()).getScalarVal();
  2618. // Otherwise, calculate and project.
  2619. return CGF.EmitComplexExpr(Op, false, true).first;
  2620. }
  2621. return Visit(Op);
  2622. }
  2623. Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
  2624. Expr *Op = E->getSubExpr();
  2625. if (Op->getType()->isAnyComplexType()) {
  2626. // If it's an l-value, load through the appropriate subobject l-value.
  2627. // Note that we have to ask E because Op might be an l-value that
  2628. // this won't work for, e.g. an Obj-C property.
  2629. if (Op->isGLValue())
  2630. return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
  2631. E->getExprLoc()).getScalarVal();
  2632. // Otherwise, calculate and project.
  2633. return CGF.EmitComplexExpr(Op, true, false).second;
  2634. }
  2635. // __imag on a scalar returns zero. Emit the subexpr to ensure side
  2636. // effects are evaluated, but not the actual value.
  2637. if (Op->isGLValue())
  2638. CGF.EmitLValue(Op);
  2639. else
  2640. CGF.EmitScalarExpr(Op, true);
  2641. return llvm::Constant::getNullValue(ConvertType(E->getType()));
  2642. }
  2643. //===----------------------------------------------------------------------===//
  2644. // Binary Operators
  2645. //===----------------------------------------------------------------------===//
  2646. BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
  2647. TestAndClearIgnoreResultAssign();
  2648. BinOpInfo Result;
  2649. Result.LHS = Visit(E->getLHS());
  2650. Result.RHS = Visit(E->getRHS());
  2651. Result.Ty = E->getType();
  2652. Result.Opcode = E->getOpcode();
  2653. Result.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
  2654. Result.E = E;
  2655. return Result;
  2656. }
  2657. LValue ScalarExprEmitter::EmitCompoundAssignLValue(
  2658. const CompoundAssignOperator *E,
  2659. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
  2660. Value *&Result) {
  2661. QualType LHSTy = E->getLHS()->getType();
  2662. BinOpInfo OpInfo;
  2663. if (E->getComputationResultType()->isAnyComplexType())
  2664. return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
  2665. // Emit the RHS first. __block variables need to have the rhs evaluated
  2666. // first, plus this should improve codegen a little.
  2667. OpInfo.RHS = Visit(E->getRHS());
  2668. OpInfo.Ty = E->getComputationResultType();
  2669. OpInfo.Opcode = E->getOpcode();
  2670. OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
  2671. OpInfo.E = E;
  2672. // Load/convert the LHS.
  2673. LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  2674. llvm::PHINode *atomicPHI = nullptr;
  2675. if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
  2676. QualType type = atomicTy->getValueType();
  2677. if (!type->isBooleanType() && type->isIntegerType() &&
  2678. !(type->isUnsignedIntegerType() &&
  2679. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
  2680. CGF.getLangOpts().getSignedOverflowBehavior() !=
  2681. LangOptions::SOB_Trapping) {
  2682. llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
  2683. llvm::Instruction::BinaryOps Op;
  2684. switch (OpInfo.Opcode) {
  2685. // We don't have atomicrmw operands for *, %, /, <<, >>
  2686. case BO_MulAssign: case BO_DivAssign:
  2687. case BO_RemAssign:
  2688. case BO_ShlAssign:
  2689. case BO_ShrAssign:
  2690. break;
  2691. case BO_AddAssign:
  2692. AtomicOp = llvm::AtomicRMWInst::Add;
  2693. Op = llvm::Instruction::Add;
  2694. break;
  2695. case BO_SubAssign:
  2696. AtomicOp = llvm::AtomicRMWInst::Sub;
  2697. Op = llvm::Instruction::Sub;
  2698. break;
  2699. case BO_AndAssign:
  2700. AtomicOp = llvm::AtomicRMWInst::And;
  2701. Op = llvm::Instruction::And;
  2702. break;
  2703. case BO_XorAssign:
  2704. AtomicOp = llvm::AtomicRMWInst::Xor;
  2705. Op = llvm::Instruction::Xor;
  2706. break;
  2707. case BO_OrAssign:
  2708. AtomicOp = llvm::AtomicRMWInst::Or;
  2709. Op = llvm::Instruction::Or;
  2710. break;
  2711. default:
  2712. llvm_unreachable("Invalid compound assignment type");
  2713. }
  2714. if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
  2715. llvm::Value *Amt = CGF.EmitToMemory(
  2716. EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
  2717. E->getExprLoc()),
  2718. LHSTy);
  2719. Value *OldVal = Builder.CreateAtomicRMW(
  2720. AtomicOp, LHSLV.getPointer(CGF), Amt,
  2721. llvm::AtomicOrdering::SequentiallyConsistent);
  2722. // Since operation is atomic, the result type is guaranteed to be the
  2723. // same as the input in LLVM terms.
  2724. Result = Builder.CreateBinOp(Op, OldVal, Amt);
  2725. return LHSLV;
  2726. }
  2727. }
  2728. // FIXME: For floating point types, we should be saving and restoring the
  2729. // floating point environment in the loop.
  2730. llvm::BasicBlock *startBB = Builder.GetInsertBlock();
  2731. llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
  2732. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2733. OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
  2734. Builder.CreateBr(opBB);
  2735. Builder.SetInsertPoint(opBB);
  2736. atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
  2737. atomicPHI->addIncoming(OpInfo.LHS, startBB);
  2738. OpInfo.LHS = atomicPHI;
  2739. }
  2740. else
  2741. OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
  2742. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
  2743. SourceLocation Loc = E->getExprLoc();
  2744. OpInfo.LHS =
  2745. EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
  2746. // Expand the binary operator.
  2747. Result = (this->*Func)(OpInfo);
  2748. // Convert the result back to the LHS type,
  2749. // potentially with Implicit Conversion sanitizer check.
  2750. Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
  2751. Loc, ScalarConversionOpts(CGF.SanOpts));
  2752. if (atomicPHI) {
  2753. llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
  2754. llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
  2755. auto Pair = CGF.EmitAtomicCompareExchange(
  2756. LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
  2757. llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
  2758. llvm::Value *success = Pair.second;
  2759. atomicPHI->addIncoming(old, curBlock);
  2760. Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
  2761. Builder.SetInsertPoint(contBB);
  2762. return LHSLV;
  2763. }
  2764. // Store the result value into the LHS lvalue. Bit-fields are handled
  2765. // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
  2766. // 'An assignment expression has the value of the left operand after the
  2767. // assignment...'.
  2768. if (LHSLV.isBitField())
  2769. CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
  2770. else
  2771. CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
  2772. if (CGF.getLangOpts().OpenMP)
  2773. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
  2774. E->getLHS());
  2775. return LHSLV;
  2776. }
  2777. Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
  2778. Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
  2779. bool Ignore = TestAndClearIgnoreResultAssign();
  2780. Value *RHS = nullptr;
  2781. LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
  2782. // If the result is clearly ignored, return now.
  2783. if (Ignore)
  2784. return nullptr;
  2785. // The result of an assignment in C is the assigned r-value.
  2786. if (!CGF.getLangOpts().CPlusPlus)
  2787. return RHS;
  2788. // If the lvalue is non-volatile, return the computed value of the assignment.
  2789. if (!LHS.isVolatileQualified())
  2790. return RHS;
  2791. // Otherwise, reload the value.
  2792. return EmitLoadOfLValue(LHS, E->getExprLoc());
  2793. }
  2794. void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
  2795. const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
  2796. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  2797. if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
  2798. Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
  2799. SanitizerKind::IntegerDivideByZero));
  2800. }
  2801. const auto *BO = cast<BinaryOperator>(Ops.E);
  2802. if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
  2803. Ops.Ty->hasSignedIntegerRepresentation() &&
  2804. !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
  2805. Ops.mayHaveIntegerOverflow()) {
  2806. llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
  2807. llvm::Value *IntMin =
  2808. Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
  2809. llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
  2810. llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
  2811. llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
  2812. llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
  2813. Checks.push_back(
  2814. std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
  2815. }
  2816. if (Checks.size() > 0)
  2817. EmitBinOpCheck(Checks, Ops);
  2818. }
  2819. Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
  2820. {
  2821. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2822. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2823. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2824. Ops.Ty->isIntegerType() &&
  2825. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2826. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2827. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
  2828. } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
  2829. Ops.Ty->isRealFloatingType() &&
  2830. Ops.mayHaveFloatDivisionByZero()) {
  2831. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2832. llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
  2833. EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
  2834. Ops);
  2835. }
  2836. }
  2837. if (Ops.Ty->isConstantMatrixType()) {
  2838. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  2839. // We need to check the types of the operands of the operator to get the
  2840. // correct matrix dimensions.
  2841. auto *BO = cast<BinaryOperator>(Ops.E);
  2842. (void)BO;
  2843. assert(
  2844. isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
  2845. "first operand must be a matrix");
  2846. assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
  2847. "second operand must be an arithmetic type");
  2848. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
  2849. return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
  2850. Ops.Ty->hasUnsignedIntegerRepresentation());
  2851. }
  2852. if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
  2853. llvm::Value *Val;
  2854. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
  2855. Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
  2856. if ((CGF.getLangOpts().OpenCL &&
  2857. !CGF.CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
  2858. (CGF.getLangOpts().HIP && CGF.getLangOpts().CUDAIsDevice &&
  2859. !CGF.CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
  2860. // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
  2861. // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
  2862. // build option allows an application to specify that single precision
  2863. // floating-point divide (x/y and 1/x) and sqrt used in the program
  2864. // source are correctly rounded.
  2865. llvm::Type *ValTy = Val->getType();
  2866. if (ValTy->isFloatTy() ||
  2867. (isa<llvm::VectorType>(ValTy) &&
  2868. cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
  2869. CGF.SetFPAccuracy(Val, 2.5);
  2870. }
  2871. return Val;
  2872. }
  2873. else if (Ops.isFixedPointOp())
  2874. return EmitFixedPointBinOp(Ops);
  2875. else if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2876. return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
  2877. else
  2878. return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
  2879. }
  2880. Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
  2881. // Rem in C can't be a floating point type: C99 6.5.5p2.
  2882. if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
  2883. CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
  2884. Ops.Ty->isIntegerType() &&
  2885. (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
  2886. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2887. llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
  2888. EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
  2889. }
  2890. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  2891. return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
  2892. else
  2893. return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
  2894. }
  2895. Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
  2896. unsigned IID;
  2897. unsigned OpID = 0;
  2898. SanitizerHandler OverflowKind;
  2899. bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
  2900. switch (Ops.Opcode) {
  2901. case BO_Add:
  2902. case BO_AddAssign:
  2903. OpID = 1;
  2904. IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
  2905. llvm::Intrinsic::uadd_with_overflow;
  2906. OverflowKind = SanitizerHandler::AddOverflow;
  2907. break;
  2908. case BO_Sub:
  2909. case BO_SubAssign:
  2910. OpID = 2;
  2911. IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
  2912. llvm::Intrinsic::usub_with_overflow;
  2913. OverflowKind = SanitizerHandler::SubOverflow;
  2914. break;
  2915. case BO_Mul:
  2916. case BO_MulAssign:
  2917. OpID = 3;
  2918. IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
  2919. llvm::Intrinsic::umul_with_overflow;
  2920. OverflowKind = SanitizerHandler::MulOverflow;
  2921. break;
  2922. default:
  2923. llvm_unreachable("Unsupported operation for overflow detection");
  2924. }
  2925. OpID <<= 1;
  2926. if (isSigned)
  2927. OpID |= 1;
  2928. CodeGenFunction::SanitizerScope SanScope(&CGF);
  2929. llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
  2930. llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
  2931. Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
  2932. Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
  2933. Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
  2934. // Handle overflow with llvm.trap if no custom handler has been specified.
  2935. const std::string *handlerName =
  2936. &CGF.getLangOpts().OverflowHandler;
  2937. if (handlerName->empty()) {
  2938. // If the signed-integer-overflow sanitizer is enabled, emit a call to its
  2939. // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
  2940. if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
  2941. llvm::Value *NotOverflow = Builder.CreateNot(overflow);
  2942. SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
  2943. : SanitizerKind::UnsignedIntegerOverflow;
  2944. EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
  2945. } else
  2946. CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
  2947. return result;
  2948. }
  2949. // Branch in case of overflow.
  2950. llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
  2951. llvm::BasicBlock *continueBB =
  2952. CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
  2953. llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
  2954. Builder.CreateCondBr(overflow, overflowBB, continueBB);
  2955. // If an overflow handler is set, then we want to call it and then use its
  2956. // result, if it returns.
  2957. Builder.SetInsertPoint(overflowBB);
  2958. // Get the overflow handler.
  2959. llvm::Type *Int8Ty = CGF.Int8Ty;
  2960. llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
  2961. llvm::FunctionType *handlerTy =
  2962. llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
  2963. llvm::FunctionCallee handler =
  2964. CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
  2965. // Sign extend the args to 64-bit, so that we can use the same handler for
  2966. // all types of overflow.
  2967. llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
  2968. llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
  2969. // Call the handler with the two arguments, the operation, and the size of
  2970. // the result.
  2971. llvm::Value *handlerArgs[] = {
  2972. lhs,
  2973. rhs,
  2974. Builder.getInt8(OpID),
  2975. Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
  2976. };
  2977. llvm::Value *handlerResult =
  2978. CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
  2979. // Truncate the result back to the desired size.
  2980. handlerResult = Builder.CreateTrunc(handlerResult, opTy);
  2981. Builder.CreateBr(continueBB);
  2982. Builder.SetInsertPoint(continueBB);
  2983. llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
  2984. phi->addIncoming(result, initialBB);
  2985. phi->addIncoming(handlerResult, overflowBB);
  2986. return phi;
  2987. }
  2988. /// Emit pointer + index arithmetic.
  2989. static Value *emitPointerArithmetic(CodeGenFunction &CGF,
  2990. const BinOpInfo &op,
  2991. bool isSubtraction) {
  2992. // Must have binary (not unary) expr here. Unary pointer
  2993. // increment/decrement doesn't use this path.
  2994. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  2995. Value *pointer = op.LHS;
  2996. Expr *pointerOperand = expr->getLHS();
  2997. Value *index = op.RHS;
  2998. Expr *indexOperand = expr->getRHS();
  2999. // In a subtraction, the LHS is always the pointer.
  3000. if (!isSubtraction && !pointer->getType()->isPointerTy()) {
  3001. std::swap(pointer, index);
  3002. std::swap(pointerOperand, indexOperand);
  3003. }
  3004. bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
  3005. unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
  3006. auto &DL = CGF.CGM.getDataLayout();
  3007. auto PtrTy = cast<llvm::PointerType>(pointer->getType());
  3008. // Some versions of glibc and gcc use idioms (particularly in their malloc
  3009. // routines) that add a pointer-sized integer (known to be a pointer value)
  3010. // to a null pointer in order to cast the value back to an integer or as
  3011. // part of a pointer alignment algorithm. This is undefined behavior, but
  3012. // we'd like to be able to compile programs that use it.
  3013. //
  3014. // Normally, we'd generate a GEP with a null-pointer base here in response
  3015. // to that code, but it's also UB to dereference a pointer created that
  3016. // way. Instead (as an acknowledged hack to tolerate the idiom) we will
  3017. // generate a direct cast of the integer value to a pointer.
  3018. //
  3019. // The idiom (p = nullptr + N) is not met if any of the following are true:
  3020. //
  3021. // The operation is subtraction.
  3022. // The index is not pointer-sized.
  3023. // The pointer type is not byte-sized.
  3024. //
  3025. if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
  3026. op.Opcode,
  3027. expr->getLHS(),
  3028. expr->getRHS()))
  3029. return CGF.Builder.CreateIntToPtr(index, pointer->getType());
  3030. if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
  3031. // Zero-extend or sign-extend the pointer value according to
  3032. // whether the index is signed or not.
  3033. index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
  3034. "idx.ext");
  3035. }
  3036. // If this is subtraction, negate the index.
  3037. if (isSubtraction)
  3038. index = CGF.Builder.CreateNeg(index, "idx.neg");
  3039. if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
  3040. CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
  3041. /*Accessed*/ false);
  3042. const PointerType *pointerType
  3043. = pointerOperand->getType()->getAs<PointerType>();
  3044. if (!pointerType) {
  3045. QualType objectType = pointerOperand->getType()
  3046. ->castAs<ObjCObjectPointerType>()
  3047. ->getPointeeType();
  3048. llvm::Value *objectSize
  3049. = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
  3050. index = CGF.Builder.CreateMul(index, objectSize);
  3051. Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
  3052. result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
  3053. return CGF.Builder.CreateBitCast(result, pointer->getType());
  3054. }
  3055. QualType elementType = pointerType->getPointeeType();
  3056. if (const VariableArrayType *vla
  3057. = CGF.getContext().getAsVariableArrayType(elementType)) {
  3058. // The element count here is the total number of non-VLA elements.
  3059. llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
  3060. // Effectively, the multiply by the VLA size is part of the GEP.
  3061. // GEP indexes are signed, and scaling an index isn't permitted to
  3062. // signed-overflow, so we use the same semantics for our explicit
  3063. // multiply. We suppress this if overflow is not undefined behavior.
  3064. llvm::Type *elemTy = pointer->getType()->getPointerElementType();
  3065. if (CGF.getLangOpts().isSignedOverflowDefined()) {
  3066. index = CGF.Builder.CreateMul(index, numElements, "vla.index");
  3067. pointer = CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
  3068. } else {
  3069. index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
  3070. pointer = CGF.EmitCheckedInBoundsGEP(
  3071. elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
  3072. "add.ptr");
  3073. }
  3074. return pointer;
  3075. }
  3076. // Explicitly handle GNU void* and function pointer arithmetic extensions. The
  3077. // GNU void* casts amount to no-ops since our void* type is i8*, but this is
  3078. // future proof.
  3079. if (elementType->isVoidType() || elementType->isFunctionType()) {
  3080. Value *result = CGF.EmitCastToVoidPtr(pointer);
  3081. result = CGF.Builder.CreateGEP(CGF.Int8Ty, result, index, "add.ptr");
  3082. return CGF.Builder.CreateBitCast(result, pointer->getType());
  3083. }
  3084. llvm::Type *elemTy = CGF.ConvertTypeForMem(elementType);
  3085. if (CGF.getLangOpts().isSignedOverflowDefined())
  3086. return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
  3087. return CGF.EmitCheckedInBoundsGEP(
  3088. elemTy, pointer, index, isSigned, isSubtraction, op.E->getExprLoc(),
  3089. "add.ptr");
  3090. }
  3091. // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
  3092. // Addend. Use negMul and negAdd to negate the first operand of the Mul or
  3093. // the add operand respectively. This allows fmuladd to represent a*b-c, or
  3094. // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
  3095. // efficient operations.
  3096. static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
  3097. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  3098. bool negMul, bool negAdd) {
  3099. assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
  3100. Value *MulOp0 = MulOp->getOperand(0);
  3101. Value *MulOp1 = MulOp->getOperand(1);
  3102. if (negMul)
  3103. MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
  3104. if (negAdd)
  3105. Addend = Builder.CreateFNeg(Addend, "neg");
  3106. Value *FMulAdd = nullptr;
  3107. if (Builder.getIsFPConstrained()) {
  3108. assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
  3109. "Only constrained operation should be created when Builder is in FP "
  3110. "constrained mode");
  3111. FMulAdd = Builder.CreateConstrainedFPCall(
  3112. CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
  3113. Addend->getType()),
  3114. {MulOp0, MulOp1, Addend});
  3115. } else {
  3116. FMulAdd = Builder.CreateCall(
  3117. CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
  3118. {MulOp0, MulOp1, Addend});
  3119. }
  3120. MulOp->eraseFromParent();
  3121. return FMulAdd;
  3122. }
  3123. // Check whether it would be legal to emit an fmuladd intrinsic call to
  3124. // represent op and if so, build the fmuladd.
  3125. //
  3126. // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
  3127. // Does NOT check the type of the operation - it's assumed that this function
  3128. // will be called from contexts where it's known that the type is contractable.
  3129. static Value* tryEmitFMulAdd(const BinOpInfo &op,
  3130. const CodeGenFunction &CGF, CGBuilderTy &Builder,
  3131. bool isSub=false) {
  3132. assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
  3133. op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
  3134. "Only fadd/fsub can be the root of an fmuladd.");
  3135. // Check whether this op is marked as fusable.
  3136. if (!op.FPFeatures.allowFPContractWithinStatement())
  3137. return nullptr;
  3138. // We have a potentially fusable op. Look for a mul on one of the operands.
  3139. // Also, make sure that the mul result isn't used directly. In that case,
  3140. // there's no point creating a muladd operation.
  3141. if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
  3142. if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  3143. LHSBinOp->use_empty())
  3144. return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
  3145. }
  3146. if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
  3147. if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
  3148. RHSBinOp->use_empty())
  3149. return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
  3150. }
  3151. if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
  3152. if (LHSBinOp->getIntrinsicID() ==
  3153. llvm::Intrinsic::experimental_constrained_fmul &&
  3154. LHSBinOp->use_empty())
  3155. return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
  3156. }
  3157. if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
  3158. if (RHSBinOp->getIntrinsicID() ==
  3159. llvm::Intrinsic::experimental_constrained_fmul &&
  3160. RHSBinOp->use_empty())
  3161. return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
  3162. }
  3163. return nullptr;
  3164. }
  3165. Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
  3166. if (op.LHS->getType()->isPointerTy() ||
  3167. op.RHS->getType()->isPointerTy())
  3168. return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
  3169. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  3170. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  3171. case LangOptions::SOB_Defined:
  3172. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  3173. case LangOptions::SOB_Undefined:
  3174. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  3175. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  3176. LLVM_FALLTHROUGH;
  3177. case LangOptions::SOB_Trapping:
  3178. if (CanElideOverflowCheck(CGF.getContext(), op))
  3179. return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
  3180. return EmitOverflowCheckedBinOp(op);
  3181. }
  3182. }
  3183. if (op.Ty->isConstantMatrixType()) {
  3184. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  3185. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
  3186. return MB.CreateAdd(op.LHS, op.RHS);
  3187. }
  3188. if (op.Ty->isUnsignedIntegerType() &&
  3189. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  3190. !CanElideOverflowCheck(CGF.getContext(), op))
  3191. return EmitOverflowCheckedBinOp(op);
  3192. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  3193. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
  3194. // Try to form an fmuladd.
  3195. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
  3196. return FMulAdd;
  3197. return Builder.CreateFAdd(op.LHS, op.RHS, "add");
  3198. }
  3199. if (op.isFixedPointOp())
  3200. return EmitFixedPointBinOp(op);
  3201. return Builder.CreateAdd(op.LHS, op.RHS, "add");
  3202. }
  3203. /// The resulting value must be calculated with exact precision, so the operands
  3204. /// may not be the same type.
  3205. Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
  3206. using llvm::APSInt;
  3207. using llvm::ConstantInt;
  3208. // This is either a binary operation where at least one of the operands is
  3209. // a fixed-point type, or a unary operation where the operand is a fixed-point
  3210. // type. The result type of a binary operation is determined by
  3211. // Sema::handleFixedPointConversions().
  3212. QualType ResultTy = op.Ty;
  3213. QualType LHSTy, RHSTy;
  3214. if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
  3215. RHSTy = BinOp->getRHS()->getType();
  3216. if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
  3217. // For compound assignment, the effective type of the LHS at this point
  3218. // is the computation LHS type, not the actual LHS type, and the final
  3219. // result type is not the type of the expression but rather the
  3220. // computation result type.
  3221. LHSTy = CAO->getComputationLHSType();
  3222. ResultTy = CAO->getComputationResultType();
  3223. } else
  3224. LHSTy = BinOp->getLHS()->getType();
  3225. } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
  3226. LHSTy = UnOp->getSubExpr()->getType();
  3227. RHSTy = UnOp->getSubExpr()->getType();
  3228. }
  3229. ASTContext &Ctx = CGF.getContext();
  3230. Value *LHS = op.LHS;
  3231. Value *RHS = op.RHS;
  3232. auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
  3233. auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
  3234. auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
  3235. auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
  3236. // Perform the actual operation.
  3237. Value *Result;
  3238. llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
  3239. switch (op.Opcode) {
  3240. case BO_AddAssign:
  3241. case BO_Add:
  3242. Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3243. break;
  3244. case BO_SubAssign:
  3245. case BO_Sub:
  3246. Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3247. break;
  3248. case BO_MulAssign:
  3249. case BO_Mul:
  3250. Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3251. break;
  3252. case BO_DivAssign:
  3253. case BO_Div:
  3254. Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3255. break;
  3256. case BO_ShlAssign:
  3257. case BO_Shl:
  3258. Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
  3259. break;
  3260. case BO_ShrAssign:
  3261. case BO_Shr:
  3262. Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
  3263. break;
  3264. case BO_LT:
  3265. return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3266. case BO_GT:
  3267. return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3268. case BO_LE:
  3269. return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3270. case BO_GE:
  3271. return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3272. case BO_EQ:
  3273. // For equality operations, we assume any padding bits on unsigned types are
  3274. // zero'd out. They could be overwritten through non-saturating operations
  3275. // that cause overflow, but this leads to undefined behavior.
  3276. return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3277. case BO_NE:
  3278. return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
  3279. case BO_Cmp:
  3280. case BO_LAnd:
  3281. case BO_LOr:
  3282. llvm_unreachable("Found unimplemented fixed point binary operation");
  3283. case BO_PtrMemD:
  3284. case BO_PtrMemI:
  3285. case BO_Rem:
  3286. case BO_Xor:
  3287. case BO_And:
  3288. case BO_Or:
  3289. case BO_Assign:
  3290. case BO_RemAssign:
  3291. case BO_AndAssign:
  3292. case BO_XorAssign:
  3293. case BO_OrAssign:
  3294. case BO_Comma:
  3295. llvm_unreachable("Found unsupported binary operation for fixed point types.");
  3296. }
  3297. bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
  3298. BinaryOperator::isShiftAssignOp(op.Opcode);
  3299. // Convert to the result type.
  3300. return FPBuilder.CreateFixedToFixed(Result, IsShift ? LHSFixedSema
  3301. : CommonFixedSema,
  3302. ResultFixedSema);
  3303. }
  3304. Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
  3305. // The LHS is always a pointer if either side is.
  3306. if (!op.LHS->getType()->isPointerTy()) {
  3307. if (op.Ty->isSignedIntegerOrEnumerationType()) {
  3308. switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
  3309. case LangOptions::SOB_Defined:
  3310. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3311. case LangOptions::SOB_Undefined:
  3312. if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
  3313. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3314. LLVM_FALLTHROUGH;
  3315. case LangOptions::SOB_Trapping:
  3316. if (CanElideOverflowCheck(CGF.getContext(), op))
  3317. return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
  3318. return EmitOverflowCheckedBinOp(op);
  3319. }
  3320. }
  3321. if (op.Ty->isConstantMatrixType()) {
  3322. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  3323. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
  3324. return MB.CreateSub(op.LHS, op.RHS);
  3325. }
  3326. if (op.Ty->isUnsignedIntegerType() &&
  3327. CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
  3328. !CanElideOverflowCheck(CGF.getContext(), op))
  3329. return EmitOverflowCheckedBinOp(op);
  3330. if (op.LHS->getType()->isFPOrFPVectorTy()) {
  3331. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
  3332. // Try to form an fmuladd.
  3333. if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
  3334. return FMulAdd;
  3335. return Builder.CreateFSub(op.LHS, op.RHS, "sub");
  3336. }
  3337. if (op.isFixedPointOp())
  3338. return EmitFixedPointBinOp(op);
  3339. return Builder.CreateSub(op.LHS, op.RHS, "sub");
  3340. }
  3341. // If the RHS is not a pointer, then we have normal pointer
  3342. // arithmetic.
  3343. if (!op.RHS->getType()->isPointerTy())
  3344. return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
  3345. // Otherwise, this is a pointer subtraction.
  3346. // Do the raw subtraction part.
  3347. llvm::Value *LHS
  3348. = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
  3349. llvm::Value *RHS
  3350. = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
  3351. Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
  3352. // Okay, figure out the element size.
  3353. const BinaryOperator *expr = cast<BinaryOperator>(op.E);
  3354. QualType elementType = expr->getLHS()->getType()->getPointeeType();
  3355. llvm::Value *divisor = nullptr;
  3356. // For a variable-length array, this is going to be non-constant.
  3357. if (const VariableArrayType *vla
  3358. = CGF.getContext().getAsVariableArrayType(elementType)) {
  3359. auto VlaSize = CGF.getVLASize(vla);
  3360. elementType = VlaSize.Type;
  3361. divisor = VlaSize.NumElts;
  3362. // Scale the number of non-VLA elements by the non-VLA element size.
  3363. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
  3364. if (!eltSize.isOne())
  3365. divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
  3366. // For everything elese, we can just compute it, safe in the
  3367. // assumption that Sema won't let anything through that we can't
  3368. // safely compute the size of.
  3369. } else {
  3370. CharUnits elementSize;
  3371. // Handle GCC extension for pointer arithmetic on void* and
  3372. // function pointer types.
  3373. if (elementType->isVoidType() || elementType->isFunctionType())
  3374. elementSize = CharUnits::One();
  3375. else
  3376. elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  3377. // Don't even emit the divide for element size of 1.
  3378. if (elementSize.isOne())
  3379. return diffInChars;
  3380. divisor = CGF.CGM.getSize(elementSize);
  3381. }
  3382. // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
  3383. // pointer difference in C is only defined in the case where both operands
  3384. // are pointing to elements of an array.
  3385. return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
  3386. }
  3387. Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
  3388. llvm::IntegerType *Ty;
  3389. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
  3390. Ty = cast<llvm::IntegerType>(VT->getElementType());
  3391. else
  3392. Ty = cast<llvm::IntegerType>(LHS->getType());
  3393. return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
  3394. }
  3395. Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
  3396. const Twine &Name) {
  3397. llvm::IntegerType *Ty;
  3398. if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
  3399. Ty = cast<llvm::IntegerType>(VT->getElementType());
  3400. else
  3401. Ty = cast<llvm::IntegerType>(LHS->getType());
  3402. if (llvm::isPowerOf2_64(Ty->getBitWidth()))
  3403. return Builder.CreateAnd(RHS, GetWidthMinusOneValue(LHS, RHS), Name);
  3404. return Builder.CreateURem(
  3405. RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
  3406. }
  3407. Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
  3408. // TODO: This misses out on the sanitizer check below.
  3409. if (Ops.isFixedPointOp())
  3410. return EmitFixedPointBinOp(Ops);
  3411. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3412. // RHS to the same size as the LHS.
  3413. Value *RHS = Ops.RHS;
  3414. if (Ops.LHS->getType() != RHS->getType())
  3415. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3416. bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
  3417. Ops.Ty->hasSignedIntegerRepresentation() &&
  3418. !CGF.getLangOpts().isSignedOverflowDefined() &&
  3419. !CGF.getLangOpts().CPlusPlus20;
  3420. bool SanitizeUnsignedBase =
  3421. CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
  3422. Ops.Ty->hasUnsignedIntegerRepresentation();
  3423. bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
  3424. bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
  3425. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3426. if (CGF.getLangOpts().OpenCL)
  3427. RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
  3428. else if ((SanitizeBase || SanitizeExponent) &&
  3429. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3430. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3431. SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
  3432. llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
  3433. llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
  3434. if (SanitizeExponent) {
  3435. Checks.push_back(
  3436. std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
  3437. }
  3438. if (SanitizeBase) {
  3439. // Check whether we are shifting any non-zero bits off the top of the
  3440. // integer. We only emit this check if exponent is valid - otherwise
  3441. // instructions below will have undefined behavior themselves.
  3442. llvm::BasicBlock *Orig = Builder.GetInsertBlock();
  3443. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  3444. llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
  3445. Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
  3446. llvm::Value *PromotedWidthMinusOne =
  3447. (RHS == Ops.RHS) ? WidthMinusOne
  3448. : GetWidthMinusOneValue(Ops.LHS, RHS);
  3449. CGF.EmitBlock(CheckShiftBase);
  3450. llvm::Value *BitsShiftedOff = Builder.CreateLShr(
  3451. Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
  3452. /*NUW*/ true, /*NSW*/ true),
  3453. "shl.check");
  3454. if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
  3455. // In C99, we are not permitted to shift a 1 bit into the sign bit.
  3456. // Under C++11's rules, shifting a 1 bit into the sign bit is
  3457. // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
  3458. // define signed left shifts, so we use the C99 and C++11 rules there).
  3459. // Unsigned shifts can always shift into the top bit.
  3460. llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
  3461. BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
  3462. }
  3463. llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
  3464. llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
  3465. CGF.EmitBlock(Cont);
  3466. llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
  3467. BaseCheck->addIncoming(Builder.getTrue(), Orig);
  3468. BaseCheck->addIncoming(ValidBase, CheckShiftBase);
  3469. Checks.push_back(std::make_pair(
  3470. BaseCheck, SanitizeSignedBase ? SanitizerKind::ShiftBase
  3471. : SanitizerKind::UnsignedShiftBase));
  3472. }
  3473. assert(!Checks.empty());
  3474. EmitBinOpCheck(Checks, Ops);
  3475. }
  3476. return Builder.CreateShl(Ops.LHS, RHS, "shl");
  3477. }
  3478. Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
  3479. // TODO: This misses out on the sanitizer check below.
  3480. if (Ops.isFixedPointOp())
  3481. return EmitFixedPointBinOp(Ops);
  3482. // LLVM requires the LHS and RHS to be the same type: promote or truncate the
  3483. // RHS to the same size as the LHS.
  3484. Value *RHS = Ops.RHS;
  3485. if (Ops.LHS->getType() != RHS->getType())
  3486. RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
  3487. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  3488. if (CGF.getLangOpts().OpenCL)
  3489. RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
  3490. else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
  3491. isa<llvm::IntegerType>(Ops.LHS->getType())) {
  3492. CodeGenFunction::SanitizerScope SanScope(&CGF);
  3493. llvm::Value *Valid =
  3494. Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
  3495. EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
  3496. }
  3497. if (Ops.Ty->hasUnsignedIntegerRepresentation())
  3498. return Builder.CreateLShr(Ops.LHS, RHS, "shr");
  3499. return Builder.CreateAShr(Ops.LHS, RHS, "shr");
  3500. }
  3501. enum IntrinsicType { VCMPEQ, VCMPGT };
  3502. // return corresponding comparison intrinsic for given vector type
  3503. static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
  3504. BuiltinType::Kind ElemKind) {
  3505. switch (ElemKind) {
  3506. default: llvm_unreachable("unexpected element type");
  3507. case BuiltinType::Char_U:
  3508. case BuiltinType::UChar:
  3509. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3510. llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
  3511. case BuiltinType::Char_S:
  3512. case BuiltinType::SChar:
  3513. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
  3514. llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
  3515. case BuiltinType::UShort:
  3516. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3517. llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
  3518. case BuiltinType::Short:
  3519. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
  3520. llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
  3521. case BuiltinType::UInt:
  3522. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3523. llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
  3524. case BuiltinType::Int:
  3525. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
  3526. llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
  3527. case BuiltinType::ULong:
  3528. case BuiltinType::ULongLong:
  3529. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3530. llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
  3531. case BuiltinType::Long:
  3532. case BuiltinType::LongLong:
  3533. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
  3534. llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
  3535. case BuiltinType::Float:
  3536. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
  3537. llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
  3538. case BuiltinType::Double:
  3539. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
  3540. llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
  3541. case BuiltinType::UInt128:
  3542. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
  3543. : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
  3544. case BuiltinType::Int128:
  3545. return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
  3546. : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
  3547. }
  3548. }
  3549. Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
  3550. llvm::CmpInst::Predicate UICmpOpc,
  3551. llvm::CmpInst::Predicate SICmpOpc,
  3552. llvm::CmpInst::Predicate FCmpOpc,
  3553. bool IsSignaling) {
  3554. TestAndClearIgnoreResultAssign();
  3555. Value *Result;
  3556. QualType LHSTy = E->getLHS()->getType();
  3557. QualType RHSTy = E->getRHS()->getType();
  3558. if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
  3559. assert(E->getOpcode() == BO_EQ ||
  3560. E->getOpcode() == BO_NE);
  3561. Value *LHS = CGF.EmitScalarExpr(E->getLHS());
  3562. Value *RHS = CGF.EmitScalarExpr(E->getRHS());
  3563. Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  3564. CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
  3565. } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
  3566. BinOpInfo BOInfo = EmitBinOps(E);
  3567. Value *LHS = BOInfo.LHS;
  3568. Value *RHS = BOInfo.RHS;
  3569. // If AltiVec, the comparison results in a numeric type, so we use
  3570. // intrinsics comparing vectors and giving 0 or 1 as a result
  3571. if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
  3572. // constants for mapping CR6 register bits to predicate result
  3573. enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
  3574. llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
  3575. // in several cases vector arguments order will be reversed
  3576. Value *FirstVecArg = LHS,
  3577. *SecondVecArg = RHS;
  3578. QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
  3579. BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
  3580. switch(E->getOpcode()) {
  3581. default: llvm_unreachable("is not a comparison operation");
  3582. case BO_EQ:
  3583. CR6 = CR6_LT;
  3584. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3585. break;
  3586. case BO_NE:
  3587. CR6 = CR6_EQ;
  3588. ID = GetIntrinsic(VCMPEQ, ElementKind);
  3589. break;
  3590. case BO_LT:
  3591. CR6 = CR6_LT;
  3592. ID = GetIntrinsic(VCMPGT, ElementKind);
  3593. std::swap(FirstVecArg, SecondVecArg);
  3594. break;
  3595. case BO_GT:
  3596. CR6 = CR6_LT;
  3597. ID = GetIntrinsic(VCMPGT, ElementKind);
  3598. break;
  3599. case BO_LE:
  3600. if (ElementKind == BuiltinType::Float) {
  3601. CR6 = CR6_LT;
  3602. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3603. std::swap(FirstVecArg, SecondVecArg);
  3604. }
  3605. else {
  3606. CR6 = CR6_EQ;
  3607. ID = GetIntrinsic(VCMPGT, ElementKind);
  3608. }
  3609. break;
  3610. case BO_GE:
  3611. if (ElementKind == BuiltinType::Float) {
  3612. CR6 = CR6_LT;
  3613. ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
  3614. }
  3615. else {
  3616. CR6 = CR6_EQ;
  3617. ID = GetIntrinsic(VCMPGT, ElementKind);
  3618. std::swap(FirstVecArg, SecondVecArg);
  3619. }
  3620. break;
  3621. }
  3622. Value *CR6Param = Builder.getInt32(CR6);
  3623. llvm::Function *F = CGF.CGM.getIntrinsic(ID);
  3624. Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
  3625. // The result type of intrinsic may not be same as E->getType().
  3626. // If E->getType() is not BoolTy, EmitScalarConversion will do the
  3627. // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
  3628. // do nothing, if ResultTy is not i1 at the same time, it will cause
  3629. // crash later.
  3630. llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
  3631. if (ResultTy->getBitWidth() > 1 &&
  3632. E->getType() == CGF.getContext().BoolTy)
  3633. Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
  3634. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3635. E->getExprLoc());
  3636. }
  3637. if (BOInfo.isFixedPointOp()) {
  3638. Result = EmitFixedPointBinOp(BOInfo);
  3639. } else if (LHS->getType()->isFPOrFPVectorTy()) {
  3640. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
  3641. if (!IsSignaling)
  3642. Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
  3643. else
  3644. Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
  3645. } else if (LHSTy->hasSignedIntegerRepresentation()) {
  3646. Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
  3647. } else {
  3648. // Unsigned integers and pointers.
  3649. if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
  3650. !isa<llvm::ConstantPointerNull>(LHS) &&
  3651. !isa<llvm::ConstantPointerNull>(RHS)) {
  3652. // Dynamic information is required to be stripped for comparisons,
  3653. // because it could leak the dynamic information. Based on comparisons
  3654. // of pointers to dynamic objects, the optimizer can replace one pointer
  3655. // with another, which might be incorrect in presence of invariant
  3656. // groups. Comparison with null is safe because null does not carry any
  3657. // dynamic information.
  3658. if (LHSTy.mayBeDynamicClass())
  3659. LHS = Builder.CreateStripInvariantGroup(LHS);
  3660. if (RHSTy.mayBeDynamicClass())
  3661. RHS = Builder.CreateStripInvariantGroup(RHS);
  3662. }
  3663. Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
  3664. }
  3665. // If this is a vector comparison, sign extend the result to the appropriate
  3666. // vector integer type and return it (don't convert to bool).
  3667. if (LHSTy->isVectorType())
  3668. return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
  3669. } else {
  3670. // Complex Comparison: can only be an equality comparison.
  3671. CodeGenFunction::ComplexPairTy LHS, RHS;
  3672. QualType CETy;
  3673. if (auto *CTy = LHSTy->getAs<ComplexType>()) {
  3674. LHS = CGF.EmitComplexExpr(E->getLHS());
  3675. CETy = CTy->getElementType();
  3676. } else {
  3677. LHS.first = Visit(E->getLHS());
  3678. LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
  3679. CETy = LHSTy;
  3680. }
  3681. if (auto *CTy = RHSTy->getAs<ComplexType>()) {
  3682. RHS = CGF.EmitComplexExpr(E->getRHS());
  3683. assert(CGF.getContext().hasSameUnqualifiedType(CETy,
  3684. CTy->getElementType()) &&
  3685. "The element types must always match.");
  3686. (void)CTy;
  3687. } else {
  3688. RHS.first = Visit(E->getRHS());
  3689. RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
  3690. assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
  3691. "The element types must always match.");
  3692. }
  3693. Value *ResultR, *ResultI;
  3694. if (CETy->isRealFloatingType()) {
  3695. // As complex comparisons can only be equality comparisons, they
  3696. // are never signaling comparisons.
  3697. ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
  3698. ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
  3699. } else {
  3700. // Complex comparisons can only be equality comparisons. As such, signed
  3701. // and unsigned opcodes are the same.
  3702. ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
  3703. ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
  3704. }
  3705. if (E->getOpcode() == BO_EQ) {
  3706. Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
  3707. } else {
  3708. assert(E->getOpcode() == BO_NE &&
  3709. "Complex comparison other than == or != ?");
  3710. Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
  3711. }
  3712. }
  3713. return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
  3714. E->getExprLoc());
  3715. }
  3716. Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  3717. bool Ignore = TestAndClearIgnoreResultAssign();
  3718. Value *RHS;
  3719. LValue LHS;
  3720. switch (E->getLHS()->getType().getObjCLifetime()) {
  3721. case Qualifiers::OCL_Strong:
  3722. std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
  3723. break;
  3724. case Qualifiers::OCL_Autoreleasing:
  3725. std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
  3726. break;
  3727. case Qualifiers::OCL_ExplicitNone:
  3728. std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
  3729. break;
  3730. case Qualifiers::OCL_Weak:
  3731. RHS = Visit(E->getRHS());
  3732. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3733. RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
  3734. break;
  3735. case Qualifiers::OCL_None:
  3736. // __block variables need to have the rhs evaluated first, plus
  3737. // this should improve codegen just a little.
  3738. RHS = Visit(E->getRHS());
  3739. LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  3740. // Store the value into the LHS. Bit-fields are handled specially
  3741. // because the result is altered by the store, i.e., [C99 6.5.16p1]
  3742. // 'An assignment expression has the value of the left operand after
  3743. // the assignment...'.
  3744. if (LHS.isBitField()) {
  3745. CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
  3746. } else {
  3747. CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
  3748. CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
  3749. }
  3750. }
  3751. // If the result is clearly ignored, return now.
  3752. if (Ignore)
  3753. return nullptr;
  3754. // The result of an assignment in C is the assigned r-value.
  3755. if (!CGF.getLangOpts().CPlusPlus)
  3756. return RHS;
  3757. // If the lvalue is non-volatile, return the computed value of the assignment.
  3758. if (!LHS.isVolatileQualified())
  3759. return RHS;
  3760. // Otherwise, reload the value.
  3761. return EmitLoadOfLValue(LHS, E->getExprLoc());
  3762. }
  3763. Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
  3764. // Perform vector logical and on comparisons with zero vectors.
  3765. if (E->getType()->isVectorType()) {
  3766. CGF.incrementProfileCounter(E);
  3767. Value *LHS = Visit(E->getLHS());
  3768. Value *RHS = Visit(E->getRHS());
  3769. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3770. if (LHS->getType()->isFPOrFPVectorTy()) {
  3771. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
  3772. CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
  3773. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3774. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3775. } else {
  3776. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3777. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3778. }
  3779. Value *And = Builder.CreateAnd(LHS, RHS);
  3780. return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
  3781. }
  3782. bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
  3783. llvm::Type *ResTy = ConvertType(E->getType());
  3784. // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
  3785. // If we have 1 && X, just emit X without inserting the control flow.
  3786. bool LHSCondVal;
  3787. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3788. if (LHSCondVal) { // If we have 1 && X, just emit X.
  3789. CGF.incrementProfileCounter(E);
  3790. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3791. // If we're generating for profiling or coverage, generate a branch to a
  3792. // block that increments the RHS counter needed to track branch condition
  3793. // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
  3794. // "FalseBlock" after the increment is done.
  3795. if (InstrumentRegions &&
  3796. CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
  3797. llvm::BasicBlock *FBlock = CGF.createBasicBlock("land.end");
  3798. llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
  3799. Builder.CreateCondBr(RHSCond, RHSBlockCnt, FBlock);
  3800. CGF.EmitBlock(RHSBlockCnt);
  3801. CGF.incrementProfileCounter(E->getRHS());
  3802. CGF.EmitBranch(FBlock);
  3803. CGF.EmitBlock(FBlock);
  3804. }
  3805. // ZExt result to int or bool.
  3806. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
  3807. }
  3808. // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
  3809. if (!CGF.ContainsLabel(E->getRHS()))
  3810. return llvm::Constant::getNullValue(ResTy);
  3811. }
  3812. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
  3813. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
  3814. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3815. // Branch on the LHS first. If it is false, go to the failure (cont) block.
  3816. CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
  3817. CGF.getProfileCount(E->getRHS()));
  3818. // Any edges into the ContBlock are now from an (indeterminate number of)
  3819. // edges from this first condition. All of these values will be false. Start
  3820. // setting up the PHI node in the Cont Block for this.
  3821. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3822. "", ContBlock);
  3823. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3824. PI != PE; ++PI)
  3825. PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
  3826. eval.begin(CGF);
  3827. CGF.EmitBlock(RHSBlock);
  3828. CGF.incrementProfileCounter(E);
  3829. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3830. eval.end(CGF);
  3831. // Reaquire the RHS block, as there may be subblocks inserted.
  3832. RHSBlock = Builder.GetInsertBlock();
  3833. // If we're generating for profiling or coverage, generate a branch on the
  3834. // RHS to a block that increments the RHS true counter needed to track branch
  3835. // condition coverage.
  3836. if (InstrumentRegions &&
  3837. CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
  3838. llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
  3839. Builder.CreateCondBr(RHSCond, RHSBlockCnt, ContBlock);
  3840. CGF.EmitBlock(RHSBlockCnt);
  3841. CGF.incrementProfileCounter(E->getRHS());
  3842. CGF.EmitBranch(ContBlock);
  3843. PN->addIncoming(RHSCond, RHSBlockCnt);
  3844. }
  3845. // Emit an unconditional branch from this block to ContBlock.
  3846. {
  3847. // There is no need to emit line number for unconditional branch.
  3848. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  3849. CGF.EmitBlock(ContBlock);
  3850. }
  3851. // Insert an entry into the phi node for the edge with the value of RHSCond.
  3852. PN->addIncoming(RHSCond, RHSBlock);
  3853. // Artificial location to preserve the scope information
  3854. {
  3855. auto NL = ApplyDebugLocation::CreateArtificial(CGF);
  3856. PN->setDebugLoc(Builder.getCurrentDebugLocation());
  3857. }
  3858. // ZExt result to int.
  3859. return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
  3860. }
  3861. Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
  3862. // Perform vector logical or on comparisons with zero vectors.
  3863. if (E->getType()->isVectorType()) {
  3864. CGF.incrementProfileCounter(E);
  3865. Value *LHS = Visit(E->getLHS());
  3866. Value *RHS = Visit(E->getRHS());
  3867. Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
  3868. if (LHS->getType()->isFPOrFPVectorTy()) {
  3869. CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
  3870. CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
  3871. LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
  3872. RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
  3873. } else {
  3874. LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
  3875. RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
  3876. }
  3877. Value *Or = Builder.CreateOr(LHS, RHS);
  3878. return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
  3879. }
  3880. bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
  3881. llvm::Type *ResTy = ConvertType(E->getType());
  3882. // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
  3883. // If we have 0 || X, just emit X without inserting the control flow.
  3884. bool LHSCondVal;
  3885. if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
  3886. if (!LHSCondVal) { // If we have 0 || X, just emit X.
  3887. CGF.incrementProfileCounter(E);
  3888. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3889. // If we're generating for profiling or coverage, generate a branch to a
  3890. // block that increments the RHS counter need to track branch condition
  3891. // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
  3892. // "FalseBlock" after the increment is done.
  3893. if (InstrumentRegions &&
  3894. CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
  3895. llvm::BasicBlock *FBlock = CGF.createBasicBlock("lor.end");
  3896. llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
  3897. Builder.CreateCondBr(RHSCond, FBlock, RHSBlockCnt);
  3898. CGF.EmitBlock(RHSBlockCnt);
  3899. CGF.incrementProfileCounter(E->getRHS());
  3900. CGF.EmitBranch(FBlock);
  3901. CGF.EmitBlock(FBlock);
  3902. }
  3903. // ZExt result to int or bool.
  3904. return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
  3905. }
  3906. // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
  3907. if (!CGF.ContainsLabel(E->getRHS()))
  3908. return llvm::ConstantInt::get(ResTy, 1);
  3909. }
  3910. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
  3911. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
  3912. CodeGenFunction::ConditionalEvaluation eval(CGF);
  3913. // Branch on the LHS first. If it is true, go to the success (cont) block.
  3914. CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
  3915. CGF.getCurrentProfileCount() -
  3916. CGF.getProfileCount(E->getRHS()));
  3917. // Any edges into the ContBlock are now from an (indeterminate number of)
  3918. // edges from this first condition. All of these values will be true. Start
  3919. // setting up the PHI node in the Cont Block for this.
  3920. llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
  3921. "", ContBlock);
  3922. for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
  3923. PI != PE; ++PI)
  3924. PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
  3925. eval.begin(CGF);
  3926. // Emit the RHS condition as a bool value.
  3927. CGF.EmitBlock(RHSBlock);
  3928. CGF.incrementProfileCounter(E);
  3929. Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
  3930. eval.end(CGF);
  3931. // Reaquire the RHS block, as there may be subblocks inserted.
  3932. RHSBlock = Builder.GetInsertBlock();
  3933. // If we're generating for profiling or coverage, generate a branch on the
  3934. // RHS to a block that increments the RHS true counter needed to track branch
  3935. // condition coverage.
  3936. if (InstrumentRegions &&
  3937. CodeGenFunction::isInstrumentedCondition(E->getRHS())) {
  3938. llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
  3939. Builder.CreateCondBr(RHSCond, ContBlock, RHSBlockCnt);
  3940. CGF.EmitBlock(RHSBlockCnt);
  3941. CGF.incrementProfileCounter(E->getRHS());
  3942. CGF.EmitBranch(ContBlock);
  3943. PN->addIncoming(RHSCond, RHSBlockCnt);
  3944. }
  3945. // Emit an unconditional branch from this block to ContBlock. Insert an entry
  3946. // into the phi node for the edge with the value of RHSCond.
  3947. CGF.EmitBlock(ContBlock);
  3948. PN->addIncoming(RHSCond, RHSBlock);
  3949. // ZExt result to int.
  3950. return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
  3951. }
  3952. Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
  3953. CGF.EmitIgnoredExpr(E->getLHS());
  3954. CGF.EnsureInsertPoint();
  3955. return Visit(E->getRHS());
  3956. }
  3957. //===----------------------------------------------------------------------===//
  3958. // Other Operators
  3959. //===----------------------------------------------------------------------===//
  3960. /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
  3961. /// expression is cheap enough and side-effect-free enough to evaluate
  3962. /// unconditionally instead of conditionally. This is used to convert control
  3963. /// flow into selects in some cases.
  3964. static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
  3965. CodeGenFunction &CGF) {
  3966. // Anything that is an integer or floating point constant is fine.
  3967. return E->IgnoreParens()->isEvaluatable(CGF.getContext());
  3968. // Even non-volatile automatic variables can't be evaluated unconditionally.
  3969. // Referencing a thread_local may cause non-trivial initialization work to
  3970. // occur. If we're inside a lambda and one of the variables is from the scope
  3971. // outside the lambda, that function may have returned already. Reading its
  3972. // locals is a bad idea. Also, these reads may introduce races there didn't
  3973. // exist in the source-level program.
  3974. }
  3975. Value *ScalarExprEmitter::
  3976. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  3977. TestAndClearIgnoreResultAssign();
  3978. // Bind the common expression if necessary.
  3979. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  3980. Expr *condExpr = E->getCond();
  3981. Expr *lhsExpr = E->getTrueExpr();
  3982. Expr *rhsExpr = E->getFalseExpr();
  3983. // If the condition constant folds and can be elided, try to avoid emitting
  3984. // the condition and the dead arm.
  3985. bool CondExprBool;
  3986. if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3987. Expr *live = lhsExpr, *dead = rhsExpr;
  3988. if (!CondExprBool) std::swap(live, dead);
  3989. // If the dead side doesn't have labels we need, just emit the Live part.
  3990. if (!CGF.ContainsLabel(dead)) {
  3991. if (CondExprBool)
  3992. CGF.incrementProfileCounter(E);
  3993. Value *Result = Visit(live);
  3994. // If the live part is a throw expression, it acts like it has a void
  3995. // type, so evaluating it returns a null Value*. However, a conditional
  3996. // with non-void type must return a non-null Value*.
  3997. if (!Result && !E->getType()->isVoidType())
  3998. Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
  3999. return Result;
  4000. }
  4001. }
  4002. // OpenCL: If the condition is a vector, we can treat this condition like
  4003. // the select function.
  4004. if ((CGF.getLangOpts().OpenCL && condExpr->getType()->isVectorType()) ||
  4005. condExpr->getType()->isExtVectorType()) {
  4006. CGF.incrementProfileCounter(E);
  4007. llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
  4008. llvm::Value *LHS = Visit(lhsExpr);
  4009. llvm::Value *RHS = Visit(rhsExpr);
  4010. llvm::Type *condType = ConvertType(condExpr->getType());
  4011. auto *vecTy = cast<llvm::FixedVectorType>(condType);
  4012. unsigned numElem = vecTy->getNumElements();
  4013. llvm::Type *elemType = vecTy->getElementType();
  4014. llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
  4015. llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
  4016. llvm::Value *tmp = Builder.CreateSExt(
  4017. TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
  4018. llvm::Value *tmp2 = Builder.CreateNot(tmp);
  4019. // Cast float to int to perform ANDs if necessary.
  4020. llvm::Value *RHSTmp = RHS;
  4021. llvm::Value *LHSTmp = LHS;
  4022. bool wasCast = false;
  4023. llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
  4024. if (rhsVTy->getElementType()->isFloatingPointTy()) {
  4025. RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
  4026. LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
  4027. wasCast = true;
  4028. }
  4029. llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
  4030. llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
  4031. llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
  4032. if (wasCast)
  4033. tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
  4034. return tmp5;
  4035. }
  4036. if (condExpr->getType()->isVectorType()) {
  4037. CGF.incrementProfileCounter(E);
  4038. llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
  4039. llvm::Value *LHS = Visit(lhsExpr);
  4040. llvm::Value *RHS = Visit(rhsExpr);
  4041. llvm::Type *CondType = ConvertType(condExpr->getType());
  4042. auto *VecTy = cast<llvm::VectorType>(CondType);
  4043. llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
  4044. CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
  4045. return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
  4046. }
  4047. // If this is a really simple expression (like x ? 4 : 5), emit this as a
  4048. // select instead of as control flow. We can only do this if it is cheap and
  4049. // safe to evaluate the LHS and RHS unconditionally.
  4050. if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
  4051. isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
  4052. llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
  4053. llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
  4054. CGF.incrementProfileCounter(E, StepV);
  4055. llvm::Value *LHS = Visit(lhsExpr);
  4056. llvm::Value *RHS = Visit(rhsExpr);
  4057. if (!LHS) {
  4058. // If the conditional has void type, make sure we return a null Value*.
  4059. assert(!RHS && "LHS and RHS types must match");
  4060. return nullptr;
  4061. }
  4062. return Builder.CreateSelect(CondV, LHS, RHS, "cond");
  4063. }
  4064. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  4065. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  4066. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  4067. CodeGenFunction::ConditionalEvaluation eval(CGF);
  4068. CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
  4069. CGF.getProfileCount(lhsExpr));
  4070. CGF.EmitBlock(LHSBlock);
  4071. CGF.incrementProfileCounter(E);
  4072. eval.begin(CGF);
  4073. Value *LHS = Visit(lhsExpr);
  4074. eval.end(CGF);
  4075. LHSBlock = Builder.GetInsertBlock();
  4076. Builder.CreateBr(ContBlock);
  4077. CGF.EmitBlock(RHSBlock);
  4078. eval.begin(CGF);
  4079. Value *RHS = Visit(rhsExpr);
  4080. eval.end(CGF);
  4081. RHSBlock = Builder.GetInsertBlock();
  4082. CGF.EmitBlock(ContBlock);
  4083. // If the LHS or RHS is a throw expression, it will be legitimately null.
  4084. if (!LHS)
  4085. return RHS;
  4086. if (!RHS)
  4087. return LHS;
  4088. // Create a PHI node for the real part.
  4089. llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
  4090. PN->addIncoming(LHS, LHSBlock);
  4091. PN->addIncoming(RHS, RHSBlock);
  4092. return PN;
  4093. }
  4094. Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
  4095. return Visit(E->getChosenSubExpr());
  4096. }
  4097. Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  4098. QualType Ty = VE->getType();
  4099. if (Ty->isVariablyModifiedType())
  4100. CGF.EmitVariablyModifiedType(Ty);
  4101. Address ArgValue = Address::invalid();
  4102. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  4103. llvm::Type *ArgTy = ConvertType(VE->getType());
  4104. // If EmitVAArg fails, emit an error.
  4105. if (!ArgPtr.isValid()) {
  4106. CGF.ErrorUnsupported(VE, "va_arg expression");
  4107. return llvm::UndefValue::get(ArgTy);
  4108. }
  4109. // FIXME Volatility.
  4110. llvm::Value *Val = Builder.CreateLoad(ArgPtr);
  4111. // If EmitVAArg promoted the type, we must truncate it.
  4112. if (ArgTy != Val->getType()) {
  4113. if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
  4114. Val = Builder.CreateIntToPtr(Val, ArgTy);
  4115. else
  4116. Val = Builder.CreateTrunc(Val, ArgTy);
  4117. }
  4118. return Val;
  4119. }
  4120. Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
  4121. return CGF.EmitBlockLiteral(block);
  4122. }
  4123. // Convert a vec3 to vec4, or vice versa.
  4124. static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
  4125. Value *Src, unsigned NumElementsDst) {
  4126. static constexpr int Mask[] = {0, 1, 2, -1};
  4127. return Builder.CreateShuffleVector(Src,
  4128. llvm::makeArrayRef(Mask, NumElementsDst));
  4129. }
  4130. // Create cast instructions for converting LLVM value \p Src to LLVM type \p
  4131. // DstTy. \p Src has the same size as \p DstTy. Both are single value types
  4132. // but could be scalar or vectors of different lengths, and either can be
  4133. // pointer.
  4134. // There are 4 cases:
  4135. // 1. non-pointer -> non-pointer : needs 1 bitcast
  4136. // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
  4137. // 3. pointer -> non-pointer
  4138. // a) pointer -> intptr_t : needs 1 ptrtoint
  4139. // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
  4140. // 4. non-pointer -> pointer
  4141. // a) intptr_t -> pointer : needs 1 inttoptr
  4142. // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
  4143. // Note: for cases 3b and 4b two casts are required since LLVM casts do not
  4144. // allow casting directly between pointer types and non-integer non-pointer
  4145. // types.
  4146. static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
  4147. const llvm::DataLayout &DL,
  4148. Value *Src, llvm::Type *DstTy,
  4149. StringRef Name = "") {
  4150. auto SrcTy = Src->getType();
  4151. // Case 1.
  4152. if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
  4153. return Builder.CreateBitCast(Src, DstTy, Name);
  4154. // Case 2.
  4155. if (SrcTy->isPointerTy() && DstTy->isPointerTy())
  4156. return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
  4157. // Case 3.
  4158. if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
  4159. // Case 3b.
  4160. if (!DstTy->isIntegerTy())
  4161. Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
  4162. // Cases 3a and 3b.
  4163. return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
  4164. }
  4165. // Case 4b.
  4166. if (!SrcTy->isIntegerTy())
  4167. Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
  4168. // Cases 4a and 4b.
  4169. return Builder.CreateIntToPtr(Src, DstTy, Name);
  4170. }
  4171. Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
  4172. Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
  4173. llvm::Type *DstTy = ConvertType(E->getType());
  4174. llvm::Type *SrcTy = Src->getType();
  4175. unsigned NumElementsSrc =
  4176. isa<llvm::VectorType>(SrcTy)
  4177. ? cast<llvm::FixedVectorType>(SrcTy)->getNumElements()
  4178. : 0;
  4179. unsigned NumElementsDst =
  4180. isa<llvm::VectorType>(DstTy)
  4181. ? cast<llvm::FixedVectorType>(DstTy)->getNumElements()
  4182. : 0;
  4183. // Going from vec3 to non-vec3 is a special case and requires a shuffle
  4184. // vector to get a vec4, then a bitcast if the target type is different.
  4185. if (NumElementsSrc == 3 && NumElementsDst != 3) {
  4186. Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
  4187. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  4188. DstTy);
  4189. Src->setName("astype");
  4190. return Src;
  4191. }
  4192. // Going from non-vec3 to vec3 is a special case and requires a bitcast
  4193. // to vec4 if the original type is not vec4, then a shuffle vector to
  4194. // get a vec3.
  4195. if (NumElementsSrc != 3 && NumElementsDst == 3) {
  4196. auto *Vec4Ty = llvm::FixedVectorType::get(
  4197. cast<llvm::VectorType>(DstTy)->getElementType(), 4);
  4198. Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
  4199. Vec4Ty);
  4200. Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
  4201. Src->setName("astype");
  4202. return Src;
  4203. }
  4204. return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
  4205. Src, DstTy, "astype");
  4206. }
  4207. Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
  4208. return CGF.EmitAtomicExpr(E).getScalarVal();
  4209. }
  4210. //===----------------------------------------------------------------------===//
  4211. // Entry Point into this File
  4212. //===----------------------------------------------------------------------===//
  4213. /// Emit the computation of the specified expression of scalar type, ignoring
  4214. /// the result.
  4215. Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
  4216. assert(E && hasScalarEvaluationKind(E->getType()) &&
  4217. "Invalid scalar expression to emit");
  4218. return ScalarExprEmitter(*this, IgnoreResultAssign)
  4219. .Visit(const_cast<Expr *>(E));
  4220. }
  4221. /// Emit a conversion from the specified type to the specified destination type,
  4222. /// both of which are LLVM scalar types.
  4223. Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
  4224. QualType DstTy,
  4225. SourceLocation Loc) {
  4226. assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
  4227. "Invalid scalar expression to emit");
  4228. return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
  4229. }
  4230. /// Emit a conversion from the specified complex type to the specified
  4231. /// destination type, where the destination type is an LLVM scalar type.
  4232. Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
  4233. QualType SrcTy,
  4234. QualType DstTy,
  4235. SourceLocation Loc) {
  4236. assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
  4237. "Invalid complex -> scalar conversion");
  4238. return ScalarExprEmitter(*this)
  4239. .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
  4240. }
  4241. llvm::Value *CodeGenFunction::
  4242. EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  4243. bool isInc, bool isPre) {
  4244. return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
  4245. }
  4246. LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
  4247. // object->isa or (*object).isa
  4248. // Generate code as for: *(Class*)object
  4249. Expr *BaseExpr = E->getBase();
  4250. Address Addr = Address::invalid();
  4251. if (BaseExpr->isPRValue()) {
  4252. Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
  4253. } else {
  4254. Addr = EmitLValue(BaseExpr).getAddress(*this);
  4255. }
  4256. // Cast the address to Class*.
  4257. Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
  4258. return MakeAddrLValue(Addr, E->getType());
  4259. }
  4260. LValue CodeGenFunction::EmitCompoundAssignmentLValue(
  4261. const CompoundAssignOperator *E) {
  4262. ScalarExprEmitter Scalar(*this);
  4263. Value *Result = nullptr;
  4264. switch (E->getOpcode()) {
  4265. #define COMPOUND_OP(Op) \
  4266. case BO_##Op##Assign: \
  4267. return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
  4268. Result)
  4269. COMPOUND_OP(Mul);
  4270. COMPOUND_OP(Div);
  4271. COMPOUND_OP(Rem);
  4272. COMPOUND_OP(Add);
  4273. COMPOUND_OP(Sub);
  4274. COMPOUND_OP(Shl);
  4275. COMPOUND_OP(Shr);
  4276. COMPOUND_OP(And);
  4277. COMPOUND_OP(Xor);
  4278. COMPOUND_OP(Or);
  4279. #undef COMPOUND_OP
  4280. case BO_PtrMemD:
  4281. case BO_PtrMemI:
  4282. case BO_Mul:
  4283. case BO_Div:
  4284. case BO_Rem:
  4285. case BO_Add:
  4286. case BO_Sub:
  4287. case BO_Shl:
  4288. case BO_Shr:
  4289. case BO_LT:
  4290. case BO_GT:
  4291. case BO_LE:
  4292. case BO_GE:
  4293. case BO_EQ:
  4294. case BO_NE:
  4295. case BO_Cmp:
  4296. case BO_And:
  4297. case BO_Xor:
  4298. case BO_Or:
  4299. case BO_LAnd:
  4300. case BO_LOr:
  4301. case BO_Assign:
  4302. case BO_Comma:
  4303. llvm_unreachable("Not valid compound assignment operators");
  4304. }
  4305. llvm_unreachable("Unhandled compound assignment operator");
  4306. }
  4307. struct GEPOffsetAndOverflow {
  4308. // The total (signed) byte offset for the GEP.
  4309. llvm::Value *TotalOffset;
  4310. // The offset overflow flag - true if the total offset overflows.
  4311. llvm::Value *OffsetOverflows;
  4312. };
  4313. /// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
  4314. /// and compute the total offset it applies from it's base pointer BasePtr.
  4315. /// Returns offset in bytes and a boolean flag whether an overflow happened
  4316. /// during evaluation.
  4317. static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
  4318. llvm::LLVMContext &VMContext,
  4319. CodeGenModule &CGM,
  4320. CGBuilderTy &Builder) {
  4321. const auto &DL = CGM.getDataLayout();
  4322. // The total (signed) byte offset for the GEP.
  4323. llvm::Value *TotalOffset = nullptr;
  4324. // Was the GEP already reduced to a constant?
  4325. if (isa<llvm::Constant>(GEPVal)) {
  4326. // Compute the offset by casting both pointers to integers and subtracting:
  4327. // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
  4328. Value *BasePtr_int =
  4329. Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
  4330. Value *GEPVal_int =
  4331. Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
  4332. TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
  4333. return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
  4334. }
  4335. auto *GEP = cast<llvm::GEPOperator>(GEPVal);
  4336. assert(GEP->getPointerOperand() == BasePtr &&
  4337. "BasePtr must be the base of the GEP.");
  4338. assert(GEP->isInBounds() && "Expected inbounds GEP");
  4339. auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
  4340. // Grab references to the signed add/mul overflow intrinsics for intptr_t.
  4341. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  4342. auto *SAddIntrinsic =
  4343. CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
  4344. auto *SMulIntrinsic =
  4345. CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
  4346. // The offset overflow flag - true if the total offset overflows.
  4347. llvm::Value *OffsetOverflows = Builder.getFalse();
  4348. /// Return the result of the given binary operation.
  4349. auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
  4350. llvm::Value *RHS) -> llvm::Value * {
  4351. assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
  4352. // If the operands are constants, return a constant result.
  4353. if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
  4354. if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
  4355. llvm::APInt N;
  4356. bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
  4357. /*Signed=*/true, N);
  4358. if (HasOverflow)
  4359. OffsetOverflows = Builder.getTrue();
  4360. return llvm::ConstantInt::get(VMContext, N);
  4361. }
  4362. }
  4363. // Otherwise, compute the result with checked arithmetic.
  4364. auto *ResultAndOverflow = Builder.CreateCall(
  4365. (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
  4366. OffsetOverflows = Builder.CreateOr(
  4367. Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
  4368. return Builder.CreateExtractValue(ResultAndOverflow, 0);
  4369. };
  4370. // Determine the total byte offset by looking at each GEP operand.
  4371. for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
  4372. GTI != GTE; ++GTI) {
  4373. llvm::Value *LocalOffset;
  4374. auto *Index = GTI.getOperand();
  4375. // Compute the local offset contributed by this indexing step:
  4376. if (auto *STy = GTI.getStructTypeOrNull()) {
  4377. // For struct indexing, the local offset is the byte position of the
  4378. // specified field.
  4379. unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
  4380. LocalOffset = llvm::ConstantInt::get(
  4381. IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
  4382. } else {
  4383. // Otherwise this is array-like indexing. The local offset is the index
  4384. // multiplied by the element size.
  4385. auto *ElementSize = llvm::ConstantInt::get(
  4386. IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
  4387. auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
  4388. LocalOffset = eval(BO_Mul, ElementSize, IndexS);
  4389. }
  4390. // If this is the first offset, set it as the total offset. Otherwise, add
  4391. // the local offset into the running total.
  4392. if (!TotalOffset || TotalOffset == Zero)
  4393. TotalOffset = LocalOffset;
  4394. else
  4395. TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
  4396. }
  4397. return {TotalOffset, OffsetOverflows};
  4398. }
  4399. Value *
  4400. CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
  4401. ArrayRef<Value *> IdxList,
  4402. bool SignedIndices, bool IsSubtraction,
  4403. SourceLocation Loc, const Twine &Name) {
  4404. llvm::Type *PtrTy = Ptr->getType();
  4405. Value *GEPVal = Builder.CreateInBoundsGEP(ElemTy, Ptr, IdxList, Name);
  4406. // If the pointer overflow sanitizer isn't enabled, do nothing.
  4407. if (!SanOpts.has(SanitizerKind::PointerOverflow))
  4408. return GEPVal;
  4409. // Perform nullptr-and-offset check unless the nullptr is defined.
  4410. bool PerformNullCheck = !NullPointerIsDefined(
  4411. Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
  4412. // Check for overflows unless the GEP got constant-folded,
  4413. // and only in the default address space
  4414. bool PerformOverflowCheck =
  4415. !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
  4416. if (!(PerformNullCheck || PerformOverflowCheck))
  4417. return GEPVal;
  4418. const auto &DL = CGM.getDataLayout();
  4419. SanitizerScope SanScope(this);
  4420. llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
  4421. GEPOffsetAndOverflow EvaluatedGEP =
  4422. EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
  4423. assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
  4424. EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
  4425. "If the offset got constant-folded, we don't expect that there was an "
  4426. "overflow.");
  4427. auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
  4428. // Common case: if the total offset is zero, and we are using C++ semantics,
  4429. // where nullptr+0 is defined, don't emit a check.
  4430. if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
  4431. return GEPVal;
  4432. // Now that we've computed the total offset, add it to the base pointer (with
  4433. // wrapping semantics).
  4434. auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
  4435. auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
  4436. llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
  4437. if (PerformNullCheck) {
  4438. // In C++, if the base pointer evaluates to a null pointer value,
  4439. // the only valid pointer this inbounds GEP can produce is also
  4440. // a null pointer, so the offset must also evaluate to zero.
  4441. // Likewise, if we have non-zero base pointer, we can not get null pointer
  4442. // as a result, so the offset can not be -intptr_t(BasePtr).
  4443. // In other words, both pointers are either null, or both are non-null,
  4444. // or the behaviour is undefined.
  4445. //
  4446. // C, however, is more strict in this regard, and gives more
  4447. // optimization opportunities: in C, additionally, nullptr+0 is undefined.
  4448. // So both the input to the 'gep inbounds' AND the output must not be null.
  4449. auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
  4450. auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
  4451. auto *Valid =
  4452. CGM.getLangOpts().CPlusPlus
  4453. ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
  4454. : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
  4455. Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
  4456. }
  4457. if (PerformOverflowCheck) {
  4458. // The GEP is valid if:
  4459. // 1) The total offset doesn't overflow, and
  4460. // 2) The sign of the difference between the computed address and the base
  4461. // pointer matches the sign of the total offset.
  4462. llvm::Value *ValidGEP;
  4463. auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
  4464. if (SignedIndices) {
  4465. // GEP is computed as `unsigned base + signed offset`, therefore:
  4466. // * If offset was positive, then the computed pointer can not be
  4467. // [unsigned] less than the base pointer, unless it overflowed.
  4468. // * If offset was negative, then the computed pointer can not be
  4469. // [unsigned] greater than the bas pointere, unless it overflowed.
  4470. auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4471. auto *PosOrZeroOffset =
  4472. Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
  4473. llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
  4474. ValidGEP =
  4475. Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
  4476. } else if (!IsSubtraction) {
  4477. // GEP is computed as `unsigned base + unsigned offset`, therefore the
  4478. // computed pointer can not be [unsigned] less than base pointer,
  4479. // unless there was an overflow.
  4480. // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
  4481. ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
  4482. } else {
  4483. // GEP is computed as `unsigned base - unsigned offset`, therefore the
  4484. // computed pointer can not be [unsigned] greater than base pointer,
  4485. // unless there was an overflow.
  4486. // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
  4487. ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
  4488. }
  4489. ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
  4490. Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
  4491. }
  4492. assert(!Checks.empty() && "Should have produced some checks.");
  4493. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
  4494. // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
  4495. llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
  4496. EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
  4497. return GEPVal;
  4498. }