CGExprScalar.cpp 183 KB

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