CGExpr.cpp 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Expr nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGCXXABI.h"
  15. #include "CGCall.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGObjCRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CGHLSLRuntime.h" // HLSL Change
  20. #include "CGRecordLayout.h"
  21. #include "CodeGenModule.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/ADT/Hashing.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/IR/MDBuilder.h"
  33. #include "llvm/Support/ConvertUTF.h"
  34. #include "llvm/Support/MathExtras.h"
  35. using namespace clang;
  36. using namespace CodeGen;
  37. //===--------------------------------------------------------------------===//
  38. // Miscellaneous Helper Methods
  39. //===--------------------------------------------------------------------===//
  40. llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
  41. unsigned addressSpace =
  42. cast<llvm::PointerType>(value->getType())->getAddressSpace();
  43. llvm::PointerType *destType = Int8PtrTy;
  44. if (addressSpace)
  45. destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
  46. if (value->getType() == destType) return value;
  47. return Builder.CreateBitCast(value, destType);
  48. }
  49. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  50. /// block.
  51. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
  52. const Twine &Name) {
  53. if (!Builder.isNamePreserving())
  54. return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
  55. return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
  56. }
  57. void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
  58. llvm::Value *Init) {
  59. auto *Store = new llvm::StoreInst(Init, Var);
  60. llvm::BasicBlock *Block = AllocaInsertPt->getParent();
  61. Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
  62. }
  63. llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
  64. const Twine &Name) {
  65. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
  66. // FIXME: Should we prefer the preferred type alignment here?
  67. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  68. Alloc->setAlignment(Align.getQuantity());
  69. return Alloc;
  70. }
  71. llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
  72. const Twine &Name) {
  73. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
  74. // FIXME: Should we prefer the preferred type alignment here?
  75. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  76. Alloc->setAlignment(Align.getQuantity());
  77. return Alloc;
  78. }
  79. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  80. /// expression and compare the result against zero, returning an Int1Ty value.
  81. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  82. PGO.setCurrentStmt(E);
  83. if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
  84. llvm::Value *MemPtr = EmitScalarExpr(E);
  85. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
  86. }
  87. QualType BoolTy = getContext().BoolTy;
  88. if (!E->getType()->isAnyComplexType())
  89. return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
  90. return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
  91. }
  92. /// EmitIgnoredExpr - Emit code to compute the specified expression,
  93. /// ignoring the result.
  94. void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
  95. if (E->isRValue())
  96. return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
  97. // Just emit it as an l-value and drop the result.
  98. EmitLValue(E);
  99. }
  100. /// EmitAnyExpr - Emit code to compute the specified expression which
  101. /// can have any type. The result is returned as an RValue struct.
  102. /// If this is an aggregate expression, AggSlot indicates where the
  103. /// result should be returned.
  104. RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
  105. AggValueSlot aggSlot,
  106. bool ignoreResult) {
  107. switch (getEvaluationKind(E->getType())) {
  108. case TEK_Scalar:
  109. return RValue::get(EmitScalarExpr(E, ignoreResult));
  110. case TEK_Complex:
  111. return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
  112. case TEK_Aggregate:
  113. if (!ignoreResult && aggSlot.isIgnored())
  114. aggSlot = CreateAggTemp(E->getType(), "agg-temp");
  115. EmitAggExpr(E, aggSlot);
  116. return aggSlot.asRValue();
  117. }
  118. llvm_unreachable("bad evaluation kind");
  119. }
  120. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  121. /// always be accessible even if no aggregate location is provided.
  122. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
  123. AggValueSlot AggSlot = AggValueSlot::ignored();
  124. if (hasAggregateEvaluationKind(E->getType()))
  125. AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
  126. return EmitAnyExpr(E, AggSlot);
  127. }
  128. /// EmitAnyExprToMem - Evaluate an expression into a given memory
  129. /// location.
  130. void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
  131. llvm::Value *Location,
  132. Qualifiers Quals,
  133. bool IsInit) {
  134. // FIXME: This function should take an LValue as an argument.
  135. switch (getEvaluationKind(E->getType())) {
  136. case TEK_Complex:
  137. EmitComplexExprIntoLValue(E,
  138. MakeNaturalAlignAddrLValue(Location, E->getType()),
  139. /*isInit*/ false);
  140. return;
  141. case TEK_Aggregate: {
  142. CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
  143. EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
  144. AggValueSlot::IsDestructed_t(IsInit),
  145. AggValueSlot::DoesNotNeedGCBarriers,
  146. AggValueSlot::IsAliased_t(!IsInit)));
  147. return;
  148. }
  149. case TEK_Scalar: {
  150. RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
  151. LValue LV = MakeAddrLValue(Location, E->getType());
  152. EmitStoreThroughLValue(RV, LV);
  153. return;
  154. }
  155. }
  156. llvm_unreachable("bad evaluation kind");
  157. }
  158. static void
  159. pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
  160. const Expr *E, llvm::Value *ReferenceTemporary) {
  161. // Objective-C++ ARC:
  162. // If we are binding a reference to a temporary that has ownership, we
  163. // need to perform retain/release operations on the temporary.
  164. //
  165. // FIXME: This should be looking at E, not M.
  166. if (CGF.getLangOpts().ObjCAutoRefCount &&
  167. M->getType()->isObjCLifetimeType()) {
  168. QualType ObjCARCReferenceLifetimeType = M->getType();
  169. switch (Qualifiers::ObjCLifetime Lifetime =
  170. ObjCARCReferenceLifetimeType.getObjCLifetime()) {
  171. case Qualifiers::OCL_None:
  172. case Qualifiers::OCL_ExplicitNone:
  173. // Carry on to normal cleanup handling.
  174. break;
  175. case Qualifiers::OCL_Autoreleasing:
  176. // Nothing to do; cleaned up by an autorelease pool.
  177. return;
  178. case Qualifiers::OCL_Strong:
  179. case Qualifiers::OCL_Weak:
  180. switch (StorageDuration Duration = M->getStorageDuration()) {
  181. case SD_Static:
  182. // Note: we intentionally do not register a cleanup to release
  183. // the object on program termination.
  184. return;
  185. case SD_Thread:
  186. // FIXME: We should probably register a cleanup in this case.
  187. return;
  188. case SD_Automatic:
  189. case SD_FullExpression:
  190. CodeGenFunction::Destroyer *Destroy;
  191. CleanupKind CleanupKind;
  192. if (Lifetime == Qualifiers::OCL_Strong) {
  193. const ValueDecl *VD = M->getExtendingDecl();
  194. bool Precise =
  195. VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
  196. CleanupKind = CGF.getARCCleanupKind();
  197. Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
  198. : &CodeGenFunction::destroyARCStrongImprecise;
  199. } else {
  200. // __weak objects always get EH cleanups; otherwise, exceptions
  201. // could cause really nasty crashes instead of mere leaks.
  202. CleanupKind = NormalAndEHCleanup;
  203. Destroy = &CodeGenFunction::destroyARCWeak;
  204. }
  205. if (Duration == SD_FullExpression)
  206. CGF.pushDestroy(CleanupKind, ReferenceTemporary,
  207. ObjCARCReferenceLifetimeType, *Destroy,
  208. CleanupKind & EHCleanup);
  209. else
  210. CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
  211. ObjCARCReferenceLifetimeType,
  212. *Destroy, CleanupKind & EHCleanup);
  213. return;
  214. case SD_Dynamic:
  215. llvm_unreachable("temporary cannot have dynamic storage duration");
  216. }
  217. llvm_unreachable("unknown storage duration");
  218. }
  219. }
  220. CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
  221. if (const RecordType *RT =
  222. E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  223. // Get the destructor for the reference temporary.
  224. auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  225. if (!ClassDecl->hasTrivialDestructor())
  226. ReferenceTemporaryDtor = ClassDecl->getDestructor();
  227. }
  228. if (!ReferenceTemporaryDtor)
  229. return;
  230. // Call the destructor for the temporary.
  231. switch (M->getStorageDuration()) {
  232. case SD_Static:
  233. case SD_Thread: {
  234. llvm::Constant *CleanupFn;
  235. llvm::Constant *CleanupArg;
  236. if (E->getType()->isArrayType()) {
  237. CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
  238. cast<llvm::Constant>(ReferenceTemporary), E->getType(),
  239. CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
  240. dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
  241. CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  242. } else {
  243. CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
  244. StructorType::Complete);
  245. CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
  246. }
  247. CGF.CGM.getCXXABI().registerGlobalDtor(
  248. CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
  249. break;
  250. }
  251. case SD_FullExpression:
  252. CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
  253. CodeGenFunction::destroyCXXObject,
  254. CGF.getLangOpts().Exceptions);
  255. break;
  256. case SD_Automatic:
  257. CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
  258. ReferenceTemporary, E->getType(),
  259. CodeGenFunction::destroyCXXObject,
  260. CGF.getLangOpts().Exceptions);
  261. break;
  262. case SD_Dynamic:
  263. llvm_unreachable("temporary cannot have dynamic storage duration");
  264. }
  265. }
  266. static llvm::Value *
  267. createReferenceTemporary(CodeGenFunction &CGF,
  268. const MaterializeTemporaryExpr *M, const Expr *Inner) {
  269. switch (M->getStorageDuration()) {
  270. case SD_FullExpression:
  271. case SD_Automatic: {
  272. // If we have a constant temporary array or record try to promote it into a
  273. // constant global under the same rules a normal constant would've been
  274. // promoted. This is easier on the optimizer and generally emits fewer
  275. // instructions.
  276. QualType Ty = Inner->getType();
  277. if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
  278. (Ty->isArrayType() || Ty->isRecordType()) &&
  279. CGF.CGM.isTypeConstant(Ty, true))
  280. if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
  281. auto *GV = new llvm::GlobalVariable(
  282. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  283. llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
  284. GV->setAlignment(
  285. CGF.getContext().getTypeAlignInChars(Ty).getQuantity());
  286. // FIXME: Should we put the new global into a COMDAT?
  287. return GV;
  288. }
  289. return CGF.CreateMemTemp(Ty, "ref.tmp");
  290. }
  291. case SD_Thread:
  292. case SD_Static:
  293. return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
  294. case SD_Dynamic:
  295. llvm_unreachable("temporary can't have dynamic storage duration");
  296. }
  297. llvm_unreachable("unknown storage duration");
  298. }
  299. LValue CodeGenFunction::
  300. EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
  301. const Expr *E = M->GetTemporaryExpr();
  302. // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
  303. // as that will cause the lifetime adjustment to be lost for ARC
  304. if (getLangOpts().ObjCAutoRefCount &&
  305. M->getType()->isObjCLifetimeType() &&
  306. M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
  307. M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  308. llvm::Value *Object = createReferenceTemporary(*this, M, E);
  309. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
  310. Object = llvm::ConstantExpr::getBitCast(
  311. Var, ConvertTypeForMem(E->getType())->getPointerTo());
  312. // We should not have emitted the initializer for this temporary as a
  313. // constant.
  314. assert(!Var->hasInitializer());
  315. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  316. }
  317. LValue RefTempDst = MakeAddrLValue(Object, M->getType());
  318. switch (getEvaluationKind(E->getType())) {
  319. default: llvm_unreachable("expected scalar or aggregate expression");
  320. case TEK_Scalar:
  321. EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
  322. break;
  323. case TEK_Aggregate: {
  324. CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
  325. EmitAggExpr(E, AggValueSlot::forAddr(Object, Alignment,
  326. E->getType().getQualifiers(),
  327. AggValueSlot::IsDestructed,
  328. AggValueSlot::DoesNotNeedGCBarriers,
  329. AggValueSlot::IsNotAliased));
  330. break;
  331. }
  332. }
  333. pushTemporaryCleanup(*this, M, E, Object);
  334. return RefTempDst;
  335. }
  336. SmallVector<const Expr *, 2> CommaLHSs;
  337. SmallVector<SubobjectAdjustment, 2> Adjustments;
  338. E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  339. for (const auto &Ignored : CommaLHSs)
  340. EmitIgnoredExpr(Ignored);
  341. if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
  342. if (opaque->getType()->isRecordType()) {
  343. assert(Adjustments.empty());
  344. return EmitOpaqueValueLValue(opaque);
  345. }
  346. }
  347. // Create and initialize the reference temporary.
  348. llvm::Value *Object = createReferenceTemporary(*this, M, E);
  349. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
  350. Object = llvm::ConstantExpr::getBitCast(
  351. Var, ConvertTypeForMem(E->getType())->getPointerTo());
  352. // If the temporary is a global and has a constant initializer or is a
  353. // constant temporary that we promoted to a global, we may have already
  354. // initialized it.
  355. if (!Var->hasInitializer()) {
  356. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  357. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  358. }
  359. } else {
  360. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  361. }
  362. pushTemporaryCleanup(*this, M, E, Object);
  363. // Perform derived-to-base casts and/or field accesses, to get from the
  364. // temporary object we created (and, potentially, for which we extended
  365. // the lifetime) to the subobject we're binding the reference to.
  366. for (unsigned I = Adjustments.size(); I != 0; --I) {
  367. SubobjectAdjustment &Adjustment = Adjustments[I-1];
  368. switch (Adjustment.Kind) {
  369. case SubobjectAdjustment::DerivedToBaseAdjustment:
  370. Object =
  371. GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
  372. Adjustment.DerivedToBase.BasePath->path_begin(),
  373. Adjustment.DerivedToBase.BasePath->path_end(),
  374. /*NullCheckValue=*/ false, E->getExprLoc());
  375. break;
  376. case SubobjectAdjustment::FieldAdjustment: {
  377. LValue LV = MakeAddrLValue(Object, E->getType());
  378. LV = EmitLValueForField(LV, Adjustment.Field);
  379. assert(LV.isSimple() &&
  380. "materialized temporary field is not a simple lvalue");
  381. Object = LV.getAddress();
  382. break;
  383. }
  384. case SubobjectAdjustment::MemberPointerAdjustment: {
  385. llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
  386. Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
  387. *this, E, Object, Ptr, Adjustment.Ptr.MPT);
  388. break;
  389. }
  390. }
  391. }
  392. return MakeAddrLValue(Object, M->getType());
  393. }
  394. RValue
  395. CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
  396. // Emit the expression as an lvalue.
  397. LValue LV = EmitLValue(E);
  398. assert(LV.isSimple());
  399. llvm::Value *Value = LV.getAddress();
  400. if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
  401. // C++11 [dcl.ref]p5 (as amended by core issue 453):
  402. // If a glvalue to which a reference is directly bound designates neither
  403. // an existing object or function of an appropriate type nor a region of
  404. // storage of suitable size and alignment to contain an object of the
  405. // reference's type, the behavior is undefined.
  406. QualType Ty = E->getType();
  407. EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
  408. }
  409. return RValue::get(Value);
  410. }
  411. /// getAccessedFieldNo - Given an encoded value and a result number, return the
  412. /// input field number being accessed.
  413. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
  414. const llvm::Constant *Elts) {
  415. return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
  416. ->getZExtValue();
  417. }
  418. /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
  419. static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
  420. llvm::Value *High) {
  421. llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
  422. llvm::Value *K47 = Builder.getInt64(47);
  423. llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
  424. llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
  425. llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
  426. llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
  427. return Builder.CreateMul(B1, KMul);
  428. }
  429. bool CodeGenFunction::sanitizePerformTypeCheck() const {
  430. return SanOpts.has(SanitizerKind::Null) |
  431. SanOpts.has(SanitizerKind::Alignment) |
  432. SanOpts.has(SanitizerKind::ObjectSize) |
  433. SanOpts.has(SanitizerKind::Vptr);
  434. }
  435. void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
  436. llvm::Value *Address, QualType Ty,
  437. CharUnits Alignment, bool SkipNullCheck) {
  438. if (!sanitizePerformTypeCheck())
  439. return;
  440. // Don't check pointers outside the default address space. The null check
  441. // isn't correct, the object-size check isn't supported by LLVM, and we can't
  442. // communicate the addresses to the runtime handler for the vptr check.
  443. if (Address->getType()->getPointerAddressSpace())
  444. return;
  445. SanitizerScope SanScope(this);
  446. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
  447. llvm::BasicBlock *Done = nullptr;
  448. bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
  449. TCK == TCK_UpcastToVirtualBase;
  450. if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
  451. !SkipNullCheck) {
  452. // The glvalue must not be an empty glvalue.
  453. llvm::Value *IsNonNull = Builder.CreateICmpNE(
  454. Address, llvm::Constant::getNullValue(Address->getType()));
  455. if (AllowNullPointers) {
  456. // When performing pointer casts, it's OK if the value is null.
  457. // Skip the remaining checks in that case.
  458. Done = createBasicBlock("null");
  459. llvm::BasicBlock *Rest = createBasicBlock("not.null");
  460. Builder.CreateCondBr(IsNonNull, Rest, Done);
  461. EmitBlock(Rest);
  462. } else {
  463. Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
  464. }
  465. }
  466. if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
  467. uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
  468. // The glvalue must refer to a large enough storage region.
  469. // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
  470. // to check this.
  471. // FIXME: Get object address space
  472. llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
  473. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
  474. llvm::Value *Min = Builder.getFalse();
  475. llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
  476. llvm::Value *LargeEnough =
  477. Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
  478. llvm::ConstantInt::get(IntPtrTy, Size));
  479. Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
  480. }
  481. uint64_t AlignVal = 0;
  482. if (SanOpts.has(SanitizerKind::Alignment)) {
  483. AlignVal = Alignment.getQuantity();
  484. if (!Ty->isIncompleteType() && !AlignVal)
  485. AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
  486. // The glvalue must be suitably aligned.
  487. if (AlignVal) {
  488. llvm::Value *Align =
  489. Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
  490. llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
  491. llvm::Value *Aligned =
  492. Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
  493. Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
  494. }
  495. }
  496. if (Checks.size() > 0) {
  497. llvm::Constant *StaticData[] = {
  498. EmitCheckSourceLocation(Loc),
  499. EmitCheckTypeDescriptor(Ty),
  500. llvm::ConstantInt::get(SizeTy, AlignVal),
  501. llvm::ConstantInt::get(Int8Ty, TCK)
  502. };
  503. EmitCheck(Checks, "type_mismatch", StaticData, Address);
  504. }
  505. // If possible, check that the vptr indicates that there is a subobject of
  506. // type Ty at offset zero within this object.
  507. //
  508. // C++11 [basic.life]p5,6:
  509. // [For storage which does not refer to an object within its lifetime]
  510. // The program has undefined behavior if:
  511. // -- the [pointer or glvalue] is used to access a non-static data member
  512. // or call a non-static member function
  513. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  514. if (SanOpts.has(SanitizerKind::Vptr) &&
  515. (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
  516. TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
  517. TCK == TCK_UpcastToVirtualBase) &&
  518. RD && RD->hasDefinition() && RD->isDynamicClass()) {
  519. // Compute a hash of the mangled name of the type.
  520. //
  521. // FIXME: This is not guaranteed to be deterministic! Move to a
  522. // fingerprinting mechanism once LLVM provides one. For the time
  523. // being the implementation happens to be deterministic.
  524. SmallString<64> MangledName;
  525. llvm::raw_svector_ostream Out(MangledName);
  526. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
  527. Out);
  528. // Blacklist based on the mangled type.
  529. if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
  530. Out.str())) {
  531. llvm::hash_code TypeHash = hash_value(Out.str());
  532. // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
  533. llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
  534. llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
  535. llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
  536. llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
  537. llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
  538. llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
  539. Hash = Builder.CreateTrunc(Hash, IntPtrTy);
  540. // Look the hash up in our cache.
  541. const int CacheSize = 128;
  542. llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
  543. llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
  544. "__ubsan_vptr_type_cache");
  545. llvm::Value *Slot = Builder.CreateAnd(Hash,
  546. llvm::ConstantInt::get(IntPtrTy,
  547. CacheSize-1));
  548. llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
  549. llvm::Value *CacheVal =
  550. Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
  551. // If the hash isn't in the cache, call a runtime handler to perform the
  552. // hard work of checking whether the vptr is for an object of the right
  553. // type. This will either fill in the cache and return, or produce a
  554. // diagnostic.
  555. llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
  556. llvm::Constant *StaticData[] = {
  557. EmitCheckSourceLocation(Loc),
  558. EmitCheckTypeDescriptor(Ty),
  559. CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
  560. llvm::ConstantInt::get(Int8Ty, TCK)
  561. };
  562. llvm::Value *DynamicData[] = { Address, Hash };
  563. EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
  564. "dynamic_type_cache_miss", StaticData, DynamicData);
  565. }
  566. }
  567. if (Done) {
  568. Builder.CreateBr(Done);
  569. EmitBlock(Done);
  570. }
  571. }
  572. /// Determine whether this expression refers to a flexible array member in a
  573. /// struct. We disable array bounds checks for such members.
  574. static bool isFlexibleArrayMemberExpr(const Expr *E) {
  575. // For compatibility with existing code, we treat arrays of length 0 or
  576. // 1 as flexible array members.
  577. const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
  578. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  579. if (CAT->getSize().ugt(1))
  580. return false;
  581. } else if (!isa<IncompleteArrayType>(AT))
  582. return false;
  583. E = E->IgnoreParens();
  584. // A flexible array member must be the last member in the class.
  585. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  586. // FIXME: If the base type of the member expr is not FD->getParent(),
  587. // this should not be treated as a flexible array member access.
  588. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  589. RecordDecl::field_iterator FI(
  590. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  591. return ++FI == FD->getParent()->field_end();
  592. }
  593. }
  594. return false;
  595. }
  596. /// If Base is known to point to the start of an array, return the length of
  597. /// that array. Return 0 if the length cannot be determined.
  598. static llvm::Value *getArrayIndexingBound(
  599. CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
  600. // For the vector indexing extension, the bound is the number of elements.
  601. if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
  602. IndexedType = Base->getType();
  603. return CGF.Builder.getInt32(VT->getNumElements());
  604. }
  605. Base = Base->IgnoreParens();
  606. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  607. if (CE->getCastKind() == CK_ArrayToPointerDecay &&
  608. !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
  609. IndexedType = CE->getSubExpr()->getType();
  610. const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
  611. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  612. return CGF.Builder.getInt(CAT->getSize());
  613. else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
  614. return CGF.getVLASize(VAT).first;
  615. }
  616. }
  617. return nullptr;
  618. }
  619. void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
  620. llvm::Value *Index, QualType IndexType,
  621. bool Accessed) {
  622. assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
  623. "should not be called unless adding bounds checks");
  624. SanitizerScope SanScope(this);
  625. QualType IndexedType;
  626. llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
  627. if (!Bound)
  628. return;
  629. bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
  630. llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
  631. llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
  632. llvm::Constant *StaticData[] = {
  633. EmitCheckSourceLocation(E->getExprLoc()),
  634. EmitCheckTypeDescriptor(IndexedType),
  635. EmitCheckTypeDescriptor(IndexType)
  636. };
  637. llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
  638. : Builder.CreateICmpULE(IndexVal, BoundVal);
  639. EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
  640. StaticData, Index);
  641. }
  642. CodeGenFunction::ComplexPairTy CodeGenFunction::
  643. EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  644. bool isInc, bool isPre) {
  645. ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
  646. llvm::Value *NextVal;
  647. if (isa<llvm::IntegerType>(InVal.first->getType())) {
  648. uint64_t AmountVal = isInc ? 1 : -1;
  649. NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
  650. // Add the inc/dec to the real part.
  651. NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  652. } else {
  653. QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
  654. llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
  655. if (!isInc)
  656. FVal.changeSign();
  657. NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
  658. // Add the inc/dec to the real part.
  659. NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  660. }
  661. ComplexPairTy IncVal(NextVal, InVal.second);
  662. // Store the updated result through the lvalue.
  663. EmitStoreOfComplex(IncVal, LV, /*init*/ false);
  664. // If this is a postinc, return the value read from memory, otherwise use the
  665. // updated value.
  666. return isPre ? IncVal : InVal;
  667. }
  668. //===----------------------------------------------------------------------===//
  669. // LValue Expression Emission
  670. //===----------------------------------------------------------------------===//
  671. RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
  672. if (Ty->isVoidType())
  673. return RValue::get(nullptr);
  674. switch (getEvaluationKind(Ty)) {
  675. case TEK_Complex: {
  676. llvm::Type *EltTy =
  677. ConvertType(Ty->castAs<ComplexType>()->getElementType());
  678. llvm::Value *U = llvm::UndefValue::get(EltTy);
  679. return RValue::getComplex(std::make_pair(U, U));
  680. }
  681. // If this is a use of an undefined aggregate type, the aggregate must have an
  682. // identifiable address. Just because the contents of the value are undefined
  683. // doesn't mean that the address can't be taken and compared.
  684. case TEK_Aggregate: {
  685. llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
  686. return RValue::getAggregate(DestPtr);
  687. }
  688. case TEK_Scalar:
  689. return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
  690. }
  691. llvm_unreachable("bad evaluation kind");
  692. }
  693. RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
  694. const char *Name) {
  695. ErrorUnsupported(E, Name);
  696. return GetUndefRValue(E->getType());
  697. }
  698. LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
  699. const char *Name) {
  700. ErrorUnsupported(E, Name);
  701. llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
  702. return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
  703. }
  704. LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
  705. LValue LV;
  706. if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
  707. LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
  708. else
  709. LV = EmitLValue(E);
  710. if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
  711. EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
  712. E->getType(), LV.getAlignment());
  713. return LV;
  714. }
  715. /// EmitLValue - Emit code to compute a designator that specifies the location
  716. /// of the expression.
  717. ///
  718. /// This can return one of two things: a simple address or a bitfield reference.
  719. /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
  720. /// an LLVM pointer type.
  721. ///
  722. /// If this returns a bitfield reference, nothing about the pointee type of the
  723. /// LLVM value is known: For example, it may not be a pointer to an integer.
  724. ///
  725. /// If this returns a normal address, and if the lvalue's C type is fixed size,
  726. /// this method guarantees that the returned pointer type will point to an LLVM
  727. /// type of the same size of the lvalue's type. If the lvalue has a variable
  728. /// length type, this is not possible.
  729. ///
  730. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  731. ApplyDebugLocation DL(*this, E);
  732. switch (E->getStmtClass()) {
  733. default: return EmitUnsupportedLValue(E, "l-value expression");
  734. case Expr::ObjCPropertyRefExprClass:
  735. llvm_unreachable("cannot emit a property reference directly");
  736. case Expr::ObjCSelectorExprClass:
  737. return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
  738. case Expr::ObjCIsaExprClass:
  739. return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
  740. case Expr::BinaryOperatorClass:
  741. return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
  742. case Expr::CompoundAssignOperatorClass: {
  743. QualType Ty = E->getType();
  744. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  745. Ty = AT->getValueType();
  746. if (!Ty->isAnyComplexType())
  747. return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  748. return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  749. }
  750. case Expr::CallExprClass:
  751. case Expr::CXXMemberCallExprClass:
  752. case Expr::CXXOperatorCallExprClass:
  753. case Expr::UserDefinedLiteralClass:
  754. return EmitCallExprLValue(cast<CallExpr>(E));
  755. case Expr::VAArgExprClass:
  756. return EmitVAArgExprLValue(cast<VAArgExpr>(E));
  757. case Expr::DeclRefExprClass:
  758. return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  759. case Expr::ParenExprClass:
  760. return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  761. case Expr::GenericSelectionExprClass:
  762. return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
  763. case Expr::PredefinedExprClass:
  764. return EmitPredefinedLValue(cast<PredefinedExpr>(E));
  765. case Expr::StringLiteralClass:
  766. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  767. case Expr::ObjCEncodeExprClass:
  768. return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
  769. case Expr::PseudoObjectExprClass:
  770. return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
  771. case Expr::InitListExprClass:
  772. return EmitInitListLValue(cast<InitListExpr>(E));
  773. case Expr::CXXTemporaryObjectExprClass:
  774. case Expr::CXXConstructExprClass:
  775. return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
  776. case Expr::CXXBindTemporaryExprClass:
  777. return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
  778. case Expr::CXXUuidofExprClass:
  779. return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
  780. case Expr::LambdaExprClass:
  781. return EmitLambdaLValue(cast<LambdaExpr>(E));
  782. case Expr::ExprWithCleanupsClass: {
  783. const auto *cleanups = cast<ExprWithCleanups>(E);
  784. enterFullExpression(cleanups);
  785. RunCleanupsScope Scope(*this);
  786. return EmitLValue(cleanups->getSubExpr());
  787. }
  788. case Expr::CXXDefaultArgExprClass:
  789. return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
  790. case Expr::CXXDefaultInitExprClass: {
  791. CXXDefaultInitExprScope Scope(*this);
  792. return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
  793. }
  794. case Expr::CXXTypeidExprClass:
  795. return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
  796. case Expr::ObjCMessageExprClass:
  797. return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
  798. case Expr::ObjCIvarRefExprClass:
  799. return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
  800. case Expr::StmtExprClass:
  801. return EmitStmtExprLValue(cast<StmtExpr>(E));
  802. case Expr::UnaryOperatorClass:
  803. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  804. case Expr::ArraySubscriptExprClass:
  805. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  806. case Expr::ExtVectorElementExprClass:
  807. return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
  808. // HLSL Change Starts
  809. case Expr::ExtMatrixElementExprClass:
  810. return EmitExtMatrixElementExpr(cast<ExtMatrixElementExpr>(E));
  811. case Expr::HLSLVectorElementExprClass:
  812. return EmitHLSLVectorElementExpr(cast<HLSLVectorElementExpr>(E));
  813. case Expr::CXXThisExprClass:
  814. return MakeAddrLValue(LoadCXXThis(), E->getType());
  815. // HLSL Change Ends
  816. case Expr::MemberExprClass:
  817. return EmitMemberExpr(cast<MemberExpr>(E));
  818. case Expr::CompoundLiteralExprClass:
  819. return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
  820. case Expr::ConditionalOperatorClass:
  821. return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
  822. case Expr::BinaryConditionalOperatorClass:
  823. return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
  824. case Expr::ChooseExprClass:
  825. return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
  826. case Expr::OpaqueValueExprClass:
  827. return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
  828. case Expr::SubstNonTypeTemplateParmExprClass:
  829. return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
  830. case Expr::ImplicitCastExprClass:
  831. case Expr::CStyleCastExprClass:
  832. case Expr::CXXFunctionalCastExprClass:
  833. case Expr::CXXStaticCastExprClass:
  834. case Expr::CXXDynamicCastExprClass:
  835. case Expr::CXXReinterpretCastExprClass:
  836. case Expr::CXXConstCastExprClass:
  837. case Expr::ObjCBridgedCastExprClass:
  838. return EmitCastLValue(cast<CastExpr>(E));
  839. case Expr::MaterializeTemporaryExprClass:
  840. return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
  841. }
  842. }
  843. /// Given an object of the given canonical type, can we safely copy a
  844. /// value out of it based on its initializer?
  845. static bool isConstantEmittableObjectType(QualType type) {
  846. assert(type.isCanonical());
  847. assert(!type->isReferenceType());
  848. // Must be const-qualified but non-volatile.
  849. Qualifiers qs = type.getLocalQualifiers();
  850. if (!qs.hasConst() || qs.hasVolatile()) return false;
  851. // Otherwise, all object types satisfy this except C++ classes with
  852. // mutable subobjects or non-trivial copy/destroy behavior.
  853. if (const auto *RT = dyn_cast<RecordType>(type))
  854. if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  855. if (RD->hasMutableFields() || !RD->isTrivial())
  856. return false;
  857. return true;
  858. }
  859. /// Can we constant-emit a load of a reference to a variable of the
  860. /// given type? This is different from predicates like
  861. /// Decl::isUsableInConstantExpressions because we do want it to apply
  862. /// in situations that don't necessarily satisfy the language's rules
  863. /// for this (e.g. C++'s ODR-use rules). For example, we want to able
  864. /// to do this with const float variables even if those variables
  865. /// aren't marked 'constexpr'.
  866. enum ConstantEmissionKind {
  867. CEK_None,
  868. CEK_AsReferenceOnly,
  869. CEK_AsValueOrReference,
  870. CEK_AsValueOnly
  871. };
  872. static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
  873. type = type.getCanonicalType();
  874. if (const auto *ref = dyn_cast<ReferenceType>(type)) {
  875. if (isConstantEmittableObjectType(ref->getPointeeType()))
  876. return CEK_AsValueOrReference;
  877. return CEK_AsReferenceOnly;
  878. }
  879. if (isConstantEmittableObjectType(type))
  880. return CEK_AsValueOnly;
  881. return CEK_None;
  882. }
  883. /// Try to emit a reference to the given value without producing it as
  884. /// an l-value. This is actually more than an optimization: we can't
  885. /// produce an l-value for variables that we never actually captured
  886. /// in a block or lambda, which means const int variables or constexpr
  887. /// literals or similar.
  888. CodeGenFunction::ConstantEmission
  889. CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
  890. ValueDecl *value = refExpr->getDecl();
  891. // The value needs to be an enum constant or a constant variable.
  892. ConstantEmissionKind CEK;
  893. if (isa<ParmVarDecl>(value)) {
  894. CEK = CEK_None;
  895. } else if (auto *var = dyn_cast<VarDecl>(value)) {
  896. CEK = checkVarTypeForConstantEmission(var->getType());
  897. } else if (isa<EnumConstantDecl>(value)) {
  898. CEK = CEK_AsValueOnly;
  899. } else {
  900. CEK = CEK_None;
  901. }
  902. if (CEK == CEK_None) return ConstantEmission();
  903. Expr::EvalResult result;
  904. bool resultIsReference;
  905. QualType resultType;
  906. // It's best to evaluate all the way as an r-value if that's permitted.
  907. if (CEK != CEK_AsReferenceOnly &&
  908. refExpr->EvaluateAsRValue(result, getContext())) {
  909. resultIsReference = false;
  910. resultType = refExpr->getType();
  911. // Otherwise, try to evaluate as an l-value.
  912. } else if (CEK != CEK_AsValueOnly &&
  913. refExpr->EvaluateAsLValue(result, getContext())) {
  914. resultIsReference = true;
  915. resultType = value->getType();
  916. // Failure.
  917. } else {
  918. return ConstantEmission();
  919. }
  920. // In any case, if the initializer has side-effects, abandon ship.
  921. if (result.HasSideEffects)
  922. return ConstantEmission();
  923. // Emit as a constant.
  924. llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
  925. // Make sure we emit a debug reference to the global variable.
  926. // This should probably fire even for
  927. if (isa<VarDecl>(value)) {
  928. if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
  929. EmitDeclRefExprDbgValue(refExpr, C);
  930. } else {
  931. assert(isa<EnumConstantDecl>(value));
  932. EmitDeclRefExprDbgValue(refExpr, C);
  933. }
  934. // If we emitted a reference constant, we need to dereference that.
  935. if (resultIsReference)
  936. return ConstantEmission::forReference(C);
  937. return ConstantEmission::forValue(C);
  938. }
  939. llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
  940. SourceLocation Loc) {
  941. return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
  942. lvalue.getAlignment().getQuantity(),
  943. lvalue.getType(), Loc, lvalue.getTBAAInfo(),
  944. lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
  945. }
  946. static bool hasBooleanRepresentation(QualType Ty) {
  947. if (Ty->isBooleanType())
  948. return true;
  949. if (const EnumType *ET = Ty->getAs<EnumType>())
  950. return ET->getDecl()->getIntegerType()->isBooleanType();
  951. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  952. return hasBooleanRepresentation(AT->getValueType());
  953. return false;
  954. }
  955. // HLSL Change Begin.
  956. static bool hasBooleanScalarOrVectorRepresentation(QualType Ty) {
  957. if (hlsl::IsHLSLVecType(Ty))
  958. return hasBooleanRepresentation(hlsl::GetElementTypeOrType(Ty));
  959. return hasBooleanRepresentation(Ty);
  960. }
  961. // HLSL Change End.
  962. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  963. llvm::APInt &Min, llvm::APInt &End,
  964. bool StrictEnums) {
  965. const EnumType *ET = Ty->getAs<EnumType>();
  966. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  967. ET && !ET->getDecl()->isFixed();
  968. bool IsBool = hasBooleanRepresentation(Ty);
  969. if (!IsBool && !IsRegularCPlusPlusEnum)
  970. return false;
  971. if (IsBool) {
  972. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  973. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  974. } else {
  975. const EnumDecl *ED = ET->getDecl();
  976. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  977. unsigned Bitwidth = LTy->getScalarSizeInBits();
  978. unsigned NumNegativeBits = ED->getNumNegativeBits();
  979. unsigned NumPositiveBits = ED->getNumPositiveBits();
  980. if (NumNegativeBits) {
  981. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  982. assert(NumBits <= Bitwidth);
  983. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  984. Min = -End;
  985. } else {
  986. assert(NumPositiveBits <= Bitwidth);
  987. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  988. Min = llvm::APInt(Bitwidth, 0);
  989. }
  990. }
  991. return true;
  992. }
  993. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  994. llvm::APInt Min, End;
  995. if (!getRangeForType(*this, Ty, Min, End,
  996. CGM.getCodeGenOpts().StrictEnums))
  997. return nullptr;
  998. llvm::MDBuilder MDHelper(getLLVMContext());
  999. return MDHelper.createRange(Min, End);
  1000. }
  1001. llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1002. unsigned Alignment, QualType Ty,
  1003. SourceLocation Loc,
  1004. llvm::MDNode *TBAAInfo,
  1005. QualType TBAABaseType,
  1006. uint64_t TBAAOffset) {
  1007. // For better performance, handle vector loads differently.
  1008. if (Ty->isVectorType()) {
  1009. llvm::Value *V;
  1010. const llvm::Type *EltTy =
  1011. cast<llvm::PointerType>(Addr->getType())->getElementType();
  1012. const auto *VTy = cast<llvm::VectorType>(EltTy);
  1013. // Handle vectors of size 3, like size 4 for better performance.
  1014. if (VTy->getNumElements() == 3) {
  1015. // Bitcast to vec4 type.
  1016. llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
  1017. 4);
  1018. llvm::PointerType *ptVec4Ty =
  1019. llvm::PointerType::get(vec4Ty,
  1020. (cast<llvm::PointerType>(
  1021. Addr->getType()))->getAddressSpace());
  1022. llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
  1023. "castToVec4");
  1024. // Now load value.
  1025. llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1026. // Shuffle vector to get vec3.
  1027. llvm::Constant *Mask[] = {
  1028. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
  1029. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
  1030. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
  1031. };
  1032. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1033. V = Builder.CreateShuffleVector(LoadVal,
  1034. llvm::UndefValue::get(vec4Ty),
  1035. MaskV, "extractVec");
  1036. return EmitFromMemory(V, Ty);
  1037. }
  1038. }
  1039. // Atomic operations have to be done on integral types.
  1040. if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
  1041. LValue lvalue = LValue::MakeAddr(Addr, Ty,
  1042. CharUnits::fromQuantity(Alignment),
  1043. getContext(), TBAAInfo);
  1044. return EmitAtomicLoad(lvalue, Loc).getScalarVal();
  1045. }
  1046. // HLSL Change Begins
  1047. if (hlsl::IsHLSLMatType(Ty)) {
  1048. // Use matrix load to keep major info.
  1049. return CGM.getHLSLRuntime().EmitHLSLMatrixLoad(*this, Addr, Ty);
  1050. }
  1051. // HLSL Change Ends
  1052. llvm::LoadInst *Load = Builder.CreateLoad(Addr);
  1053. if (Volatile)
  1054. Load->setVolatile(true);
  1055. if (Alignment)
  1056. Load->setAlignment(Alignment);
  1057. if (TBAAInfo) {
  1058. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1059. TBAAOffset);
  1060. if (TBAAPath)
  1061. CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
  1062. }
  1063. bool NeedsBoolCheck =
  1064. SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
  1065. bool NeedsEnumCheck =
  1066. SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
  1067. if (NeedsBoolCheck || NeedsEnumCheck) {
  1068. SanitizerScope SanScope(this);
  1069. llvm::APInt Min, End;
  1070. if (getRangeForType(*this, Ty, Min, End, true)) {
  1071. --End;
  1072. llvm::Value *Check;
  1073. if (!Min)
  1074. Check = Builder.CreateICmpULE(
  1075. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1076. else {
  1077. llvm::Value *Upper = Builder.CreateICmpSLE(
  1078. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1079. llvm::Value *Lower = Builder.CreateICmpSGE(
  1080. Load, llvm::ConstantInt::get(getLLVMContext(), Min));
  1081. Check = Builder.CreateAnd(Upper, Lower);
  1082. }
  1083. llvm::Constant *StaticArgs[] = {
  1084. EmitCheckSourceLocation(Loc),
  1085. EmitCheckTypeDescriptor(Ty)
  1086. };
  1087. SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1088. EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
  1089. EmitCheckValue(Load));
  1090. }
  1091. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1092. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1093. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1094. return EmitFromMemory(Load, Ty);
  1095. }
  1096. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1097. // HLSL Change Begin.
  1098. // Bool scalar and vectors have a different representation in memory than in registers.
  1099. if (hasBooleanScalarOrVectorRepresentation(Ty)) {
  1100. if (Value->getType()->getScalarType()->isIntegerTy(1))
  1101. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1102. }
  1103. // HLSL Change End.
  1104. return Value;
  1105. }
  1106. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1107. // HLSL Change Begin.
  1108. // Bool scalar and vectors have a different representation in memory than in registers.
  1109. if (hasBooleanScalarOrVectorRepresentation(Ty)) {
  1110. // Use ne v, 0 to convert to i1 instead of trunc.
  1111. return Builder.CreateICmpNE(
  1112. Value, llvm::ConstantVector::getNullValue(Value->getType()), "tobool");
  1113. }
  1114. // HLSL Change End.
  1115. return Value;
  1116. }
  1117. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1118. bool Volatile, unsigned Alignment,
  1119. QualType Ty, llvm::MDNode *TBAAInfo,
  1120. bool isInit, QualType TBAABaseType,
  1121. uint64_t TBAAOffset) {
  1122. // Handle vectors differently to get better performance.
  1123. if (Ty->isVectorType()) {
  1124. llvm::Type *SrcTy = Value->getType();
  1125. auto *VecTy = cast<llvm::VectorType>(SrcTy);
  1126. // Handle vec3 special.
  1127. if (VecTy->getNumElements() == 3) {
  1128. llvm::LLVMContext &VMContext = getLLVMContext();
  1129. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1130. SmallVector<llvm::Constant*, 4> Mask;
  1131. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1132. 0));
  1133. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1134. 1));
  1135. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1136. 2));
  1137. Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
  1138. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1139. Value = Builder.CreateShuffleVector(Value,
  1140. llvm::UndefValue::get(VecTy),
  1141. MaskV, "extractVec");
  1142. SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
  1143. }
  1144. auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
  1145. if (DstPtr->getElementType() != SrcTy) {
  1146. llvm::Type *MemTy =
  1147. llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
  1148. Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
  1149. }
  1150. }
  1151. Value = EmitToMemory(Value, Ty);
  1152. if (Ty->isAtomicType() ||
  1153. (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
  1154. EmitAtomicStore(RValue::get(Value),
  1155. LValue::MakeAddr(Addr, Ty,
  1156. CharUnits::fromQuantity(Alignment),
  1157. getContext(), TBAAInfo),
  1158. isInit);
  1159. return;
  1160. }
  1161. // HLSL Change Begins
  1162. if (hlsl::IsHLSLMatType(Ty)) {
  1163. // Use matrix store to keep major info.
  1164. CGM.getHLSLRuntime().EmitHLSLMatrixStore(*this, Value, Addr, Ty);
  1165. return;
  1166. }
  1167. // HLSL Change Ends
  1168. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1169. if (Alignment)
  1170. Store->setAlignment(Alignment);
  1171. if (TBAAInfo) {
  1172. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1173. TBAAOffset);
  1174. if (TBAAPath)
  1175. CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
  1176. }
  1177. }
  1178. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1179. bool isInit) {
  1180. EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
  1181. lvalue.getAlignment().getQuantity(), lvalue.getType(),
  1182. lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
  1183. lvalue.getTBAAOffset());
  1184. }
  1185. // HLSL Change Begin - find immediate value for literal.
  1186. static llvm::Value *GetStoredValue(llvm::Value *Ptr) {
  1187. llvm::Value *V = nullptr;
  1188. for (llvm::User *U : Ptr->users()) {
  1189. if (llvm::StoreInst *ST = dyn_cast<llvm::StoreInst>(U)) {
  1190. if (V) {
  1191. // More than one store.
  1192. // Skip.
  1193. V = nullptr;
  1194. break;
  1195. }
  1196. V = ST->getValueOperand();
  1197. }
  1198. }
  1199. return V;
  1200. }
  1201. static bool IsLiteralType(QualType QT) {
  1202. if (const BuiltinType *BTy = QT->getAs<BuiltinType>()) {
  1203. if (BTy->getKind() == BuiltinType::LitFloat ||
  1204. BTy->getKind() == BuiltinType::LitInt)
  1205. return true;
  1206. }
  1207. return false;
  1208. }
  1209. // HLSL Change End.
  1210. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1211. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1212. /// returning the rvalue.
  1213. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1214. if (LV.isObjCWeak()) {
  1215. // load of a __weak object.
  1216. llvm::Value *AddrWeakObj = LV.getAddress();
  1217. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1218. AddrWeakObj));
  1219. }
  1220. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1221. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
  1222. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1223. return RValue::get(Object);
  1224. }
  1225. if (LV.isSimple()) {
  1226. assert(!LV.getType()->isFunctionType());
  1227. // HLSL Change Begin - find immediate value for literal.
  1228. if (IsLiteralType(LV.getType())) {
  1229. // The value must be stored only once.
  1230. // Scan all use to find it.
  1231. llvm::Value *Ptr = LV.getAddress();
  1232. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1233. return RValue::get(V);
  1234. }
  1235. }
  1236. if (hlsl::IsHLSLAggregateType(LV.getType())) {
  1237. // We cannot load the value because we don't expect to ever have
  1238. // user-defined struct or array-typed llvm registers, only pointers to them.
  1239. // To preserve the snapshot semantics of LValue loads, we copy the
  1240. // value to a temporary and return a pointer to it.
  1241. llvm::Value *Alloca = CreateMemTemp(LV.getType(), "rval");
  1242. auto CharSizeAlignPair = getContext().getTypeInfoInChars(LV.getType());
  1243. Builder.CreateMemCpy(Alloca, LV.getAddress(),
  1244. static_cast<uint64_t>(CharSizeAlignPair.first.getQuantity()),
  1245. static_cast<unsigned>(CharSizeAlignPair.second.getQuantity()));
  1246. return RValue::get(Alloca);
  1247. }
  1248. // HLSL Change End.
  1249. // Everything needs a load.
  1250. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1251. }
  1252. if (LV.isVectorElt()) {
  1253. // HLSL Change Begin - find immediate value for literal.
  1254. if (IsLiteralType(LV.getType())) {
  1255. // The value must be stored only once.
  1256. // Scan all use to find it.
  1257. llvm::Value *Ptr = LV.getAddress();
  1258. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1259. return RValue::get(Builder.CreateExtractElement(V,
  1260. LV.getVectorIdx(), "vecext"));
  1261. }
  1262. }
  1263. // HLSL Change End.
  1264. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
  1265. LV.isVolatileQualified());
  1266. Load->setAlignment(LV.getAlignment().getQuantity());
  1267. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1268. "vecext"));
  1269. }
  1270. // If this is a reference to a subset of the elements of a vector, either
  1271. // shuffle the input or extract/insert them as appropriate.
  1272. if (LV.isExtVectorElt())
  1273. return EmitLoadOfExtVectorElementLValue(LV);
  1274. // Global Register variables always invoke intrinsics
  1275. if (LV.isGlobalReg())
  1276. return EmitLoadOfGlobalRegLValue(LV);
  1277. // HLSL Change Starts
  1278. if (LV.isExtMatrixElt())
  1279. return EmitLoadOfExtMatrixElementLValue(LV);
  1280. // HLSL Change Ends
  1281. assert(LV.isBitField() && "Unknown LValue type!");
  1282. return EmitLoadOfBitfieldLValue(LV);
  1283. }
  1284. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
  1285. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1286. CharUnits Align = LV.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1287. // Get the output type.
  1288. llvm::Type *ResLTy = ConvertType(LV.getType());
  1289. llvm::Value *Ptr = LV.getBitFieldAddr();
  1290. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1291. LV.isVolatileQualified(),
  1292. "bf.load");
  1293. if (Info.IsSigned) {
  1294. assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
  1295. unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
  1296. if (HighBits)
  1297. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1298. if (Info.Offset + HighBits)
  1299. Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
  1300. } else {
  1301. if (Info.Offset)
  1302. Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
  1303. if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
  1304. Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
  1305. Info.Size),
  1306. "bf.clear");
  1307. }
  1308. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1309. return RValue::get(Val);
  1310. }
  1311. // If this is a reference to a subset of the elements of a vector, create an
  1312. // appropriate shufflevector.
  1313. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1314. llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
  1315. LV.isVolatileQualified());
  1316. Load->setAlignment(LV.getAlignment().getQuantity());
  1317. llvm::Value *Vec = Load;
  1318. Vec = EmitFromMemory(Vec, LV.getType()); // HLSL Change
  1319. const llvm::Constant *Elts = LV.getExtVectorElts();
  1320. // If the result of the expression is a non-vector type, we must be extracting
  1321. // a single element. Just codegen as an extractelement.
  1322. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1323. // HLSL Change Starts
  1324. if (ExprVT == nullptr && getContext().getLangOpts().HLSL)
  1325. ExprVT =
  1326. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), LV.getType());
  1327. // HLSL Change Ends
  1328. // HLSL Change Begin - find immediate value for literal.
  1329. QualType QT = LV.getType();
  1330. if (ExprVT) {
  1331. QT = ExprVT->getElementType();
  1332. }
  1333. if (IsLiteralType(QT)) {
  1334. // The value must be stored only once.
  1335. // Scan all use to find it.
  1336. llvm::Value *Ptr = LV.getExtVectorAddr();
  1337. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1338. Vec = V;
  1339. }
  1340. }
  1341. // HLSL Change End.
  1342. if (!ExprVT) {
  1343. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1344. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1345. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1346. }
  1347. // Always use shuffle vector to try to retain the original program structure
  1348. unsigned NumResultElts = ExprVT->getNumElements();
  1349. SmallVector<llvm::Constant*, 4> Mask;
  1350. for (unsigned i = 0; i != NumResultElts; ++i)
  1351. Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
  1352. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1353. Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
  1354. MaskV);
  1355. return RValue::get(Vec);
  1356. }
  1357. /// @brief Generates lvalue for partial ext_vector access.
  1358. llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1359. llvm::Value *VectorAddress = LV.getExtVectorAddr();
  1360. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1361. QualType EQT = ExprVT->getElementType();
  1362. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1363. llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
  1364. llvm::Value *CastToPointerElement =
  1365. Builder.CreateBitCast(VectorAddress,
  1366. VectorElementPtrToTy, "conv.ptr.element");
  1367. const llvm::Constant *Elts = LV.getExtVectorElts();
  1368. unsigned ix = getAccessedFieldNo(0, Elts);
  1369. llvm::Value *VectorBasePtrPlusIx =
  1370. Builder.CreateInBoundsGEP(CastToPointerElement,
  1371. llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
  1372. return VectorBasePtrPlusIx;
  1373. }
  1374. /// @brief Load of global gamed gegisters are always calls to intrinsics.
  1375. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1376. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1377. "Bad type for register variable");
  1378. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1379. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1380. // We accept integer and pointer types only
  1381. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1382. llvm::Type *Ty = OrigTy;
  1383. if (OrigTy->isPointerTy())
  1384. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1385. llvm::Type *Types[] = { Ty };
  1386. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1387. llvm::Value *Call = Builder.CreateCall(
  1388. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1389. if (OrigTy->isPointerTy())
  1390. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1391. return RValue::get(Call);
  1392. }
  1393. // HLSL Change Starts
  1394. RValue CodeGenFunction::EmitLoadOfExtMatrixElementLValue(LValue LV) {
  1395. // TODO: Matrix swizzle members - emit
  1396. return RValue();
  1397. }
  1398. // HLSL Change Ends
  1399. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1400. /// lvalue, where both are guaranteed to the have the same type, and that type
  1401. /// is 'Ty'.
  1402. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1403. bool isInit) {
  1404. if (!Dst.isSimple()) {
  1405. if (Dst.isVectorElt()) {
  1406. // Read/modify/write the vector, inserting the new element.
  1407. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
  1408. Dst.isVolatileQualified());
  1409. Load->setAlignment(Dst.getAlignment().getQuantity());
  1410. llvm::Value *Vec = Load;
  1411. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1412. Dst.getVectorIdx(), "vecins");
  1413. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
  1414. Dst.isVolatileQualified());
  1415. Store->setAlignment(Dst.getAlignment().getQuantity());
  1416. return;
  1417. }
  1418. // If this is an update of extended vector elements, insert them as
  1419. // appropriate.
  1420. if (Dst.isExtVectorElt())
  1421. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1422. if (Dst.isGlobalReg())
  1423. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1424. assert(Dst.isBitField() && "Unknown LValue type");
  1425. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1426. }
  1427. // There's special magic for assigning into an ARC-qualified l-value.
  1428. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1429. switch (Lifetime) {
  1430. case Qualifiers::OCL_None:
  1431. llvm_unreachable("present but none");
  1432. case Qualifiers::OCL_ExplicitNone:
  1433. // nothing special
  1434. break;
  1435. case Qualifiers::OCL_Strong:
  1436. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1437. return;
  1438. case Qualifiers::OCL_Weak:
  1439. EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
  1440. return;
  1441. case Qualifiers::OCL_Autoreleasing:
  1442. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1443. Src.getScalarVal()));
  1444. // fall into the normal path
  1445. break;
  1446. }
  1447. }
  1448. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1449. // load of a __weak object.
  1450. llvm::Value *LvalueDst = Dst.getAddress();
  1451. llvm::Value *src = Src.getScalarVal();
  1452. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1453. return;
  1454. }
  1455. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1456. // load of a __strong object.
  1457. llvm::Value *LvalueDst = Dst.getAddress();
  1458. llvm::Value *src = Src.getScalarVal();
  1459. if (Dst.isObjCIvar()) {
  1460. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1461. llvm::Type *ResultType = ConvertType(getContext().LongTy);
  1462. llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
  1463. llvm::Value *dst = RHS;
  1464. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1465. llvm::Value *LHS =
  1466. Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
  1467. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1468. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1469. BytesBetween);
  1470. } else if (Dst.isGlobalObjCRef()) {
  1471. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1472. Dst.isThreadLocalRef());
  1473. }
  1474. else
  1475. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1476. return;
  1477. }
  1478. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1479. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1480. }
  1481. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1482. llvm::Value **Result) {
  1483. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1484. CharUnits Align = Dst.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1485. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1486. llvm::Value *Ptr = Dst.getBitFieldAddr();
  1487. // Get the source value, truncated to the width of the bit-field.
  1488. llvm::Value *SrcVal = Src.getScalarVal();
  1489. // Cast the source to the storage type and shift it into place.
  1490. SrcVal = Builder.CreateIntCast(SrcVal,
  1491. Ptr->getType()->getPointerElementType(),
  1492. /*IsSigned=*/false);
  1493. llvm::Value *MaskedVal = SrcVal;
  1494. // See if there are other bits in the bitfield's storage we'll need to load
  1495. // and mask together with source before storing.
  1496. if (Info.StorageSize != Info.Size) {
  1497. assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
  1498. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1499. Dst.isVolatileQualified(),
  1500. "bf.load");
  1501. // Mask the source value as needed.
  1502. if (!hasBooleanRepresentation(Dst.getType()))
  1503. SrcVal = Builder.CreateAnd(SrcVal,
  1504. llvm::APInt::getLowBitsSet(Info.StorageSize,
  1505. Info.Size),
  1506. "bf.value");
  1507. MaskedVal = SrcVal;
  1508. if (Info.Offset)
  1509. SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
  1510. // Mask out the original value.
  1511. Val = Builder.CreateAnd(Val,
  1512. ~llvm::APInt::getBitsSet(Info.StorageSize,
  1513. Info.Offset,
  1514. Info.Offset + Info.Size),
  1515. "bf.clear");
  1516. // Or together the unchanged values and the source value.
  1517. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1518. } else {
  1519. assert(Info.Offset == 0);
  1520. }
  1521. // Write the new value back out.
  1522. Builder.CreateAlignedStore(SrcVal, Ptr, Align.getQuantity(),
  1523. Dst.isVolatileQualified());
  1524. // Return the new value of the bit-field, if requested.
  1525. if (Result) {
  1526. llvm::Value *ResultVal = MaskedVal;
  1527. // Sign extend the value if needed.
  1528. if (Info.IsSigned) {
  1529. assert(Info.Size <= Info.StorageSize);
  1530. unsigned HighBits = Info.StorageSize - Info.Size;
  1531. if (HighBits) {
  1532. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1533. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1534. }
  1535. }
  1536. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1537. "bf.result.cast");
  1538. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1539. }
  1540. }
  1541. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1542. LValue Dst) {
  1543. // This access turns into a read/modify/write of the vector. Load the input
  1544. // value now.
  1545. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
  1546. Dst.isVolatileQualified());
  1547. Load->setAlignment(Dst.getAlignment().getQuantity());
  1548. llvm::Value *Vec = Load;
  1549. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1550. llvm::Value *SrcVal = Src.getScalarVal();
  1551. // HLSL Change Starts
  1552. SrcVal = EmitToMemory(SrcVal, Dst.getType());
  1553. const VectorType *VTy = Dst.getType()->getAs<VectorType>();
  1554. if (VTy == nullptr && getContext().getLangOpts().HLSL)
  1555. VTy =
  1556. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), Dst.getType());
  1557. llvm::Value * VecDstPtr = Dst.getExtVectorAddr();
  1558. llvm::Value *Zero = Builder.getInt32(0);
  1559. if (VTy) {
  1560. llvm::Type *VecTy = VecDstPtr->getType()->getPointerElementType();
  1561. unsigned NumSrcElts = VTy->getNumElements();
  1562. if (VecTy->getVectorNumElements() == NumSrcElts) {
  1563. // Full vector write, create one store.
  1564. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1565. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1566. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1567. Vec = Builder.CreateInsertElement(Vec, SrcElt, Elt);
  1568. }
  1569. }
  1570. Builder.CreateStore(Vec, VecDstPtr);
  1571. } else {
  1572. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1573. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1574. llvm::Value *EltGEP = Builder.CreateGEP(VecDstPtr, {Zero, Elt});
  1575. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1576. Builder.CreateStore(SrcElt, EltGEP);
  1577. }
  1578. }
  1579. }
  1580. } else {
  1581. // If the Src is a scalar (not a vector) it must be updating one element.
  1582. llvm::Value *EltGEP = Builder.CreateGEP(
  1583. VecDstPtr, {Zero, Elts->getAggregateElement((unsigned)0)});
  1584. Builder.CreateStore(SrcVal, EltGEP);
  1585. }
  1586. return;
  1587. // HLSL Change Ends
  1588. if (VTy) { // HLSL Change
  1589. unsigned NumSrcElts = VTy->getNumElements();
  1590. unsigned NumDstElts =
  1591. cast<llvm::VectorType>(Vec->getType())->getNumElements();
  1592. if (NumDstElts == NumSrcElts) {
  1593. // Use shuffle vector is the src and destination are the same number of
  1594. // elements and restore the vector mask since it is on the side it will be
  1595. // stored.
  1596. SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
  1597. for (unsigned i = 0; i != NumSrcElts; ++i)
  1598. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
  1599. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1600. Vec = Builder.CreateShuffleVector(SrcVal,
  1601. llvm::UndefValue::get(Vec->getType()),
  1602. MaskV);
  1603. } else if (NumDstElts > NumSrcElts) {
  1604. // Extended the source vector to the same length and then shuffle it
  1605. // into the destination.
  1606. // FIXME: since we're shuffling with undef, can we just use the indices
  1607. // into that? This could be simpler.
  1608. SmallVector<llvm::Constant*, 4> ExtMask;
  1609. for (unsigned i = 0; i != NumSrcElts; ++i)
  1610. ExtMask.push_back(Builder.getInt32(i));
  1611. ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
  1612. llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
  1613. llvm::Value *ExtSrcVal =
  1614. Builder.CreateShuffleVector(SrcVal,
  1615. llvm::UndefValue::get(SrcVal->getType()),
  1616. ExtMaskV);
  1617. // build identity
  1618. SmallVector<llvm::Constant*, 4> Mask;
  1619. for (unsigned i = 0; i != NumDstElts; ++i)
  1620. Mask.push_back(Builder.getInt32(i));
  1621. // When the vector size is odd and .odd or .hi is used, the last element
  1622. // of the Elts constant array will be one past the size of the vector.
  1623. // Ignore the last element here, if it is greater than the mask size.
  1624. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  1625. NumSrcElts--;
  1626. // modify when what gets shuffled in
  1627. for (unsigned i = 0; i != NumSrcElts; ++i)
  1628. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
  1629. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1630. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
  1631. } else {
  1632. // We should never shorten the vector
  1633. llvm_unreachable("unexpected shorten vector length");
  1634. }
  1635. } else {
  1636. // If the Src is a scalar (not a vector) it must be updating one element.
  1637. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1638. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1639. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  1640. }
  1641. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
  1642. Dst.isVolatileQualified());
  1643. Store->setAlignment(Dst.getAlignment().getQuantity());
  1644. }
  1645. /// @brief Store of global named registers are always calls to intrinsics.
  1646. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  1647. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  1648. "Bad type for register variable");
  1649. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1650. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  1651. assert(RegName && "Register LValue is not metadata");
  1652. // We accept integer and pointer types only
  1653. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  1654. llvm::Type *Ty = OrigTy;
  1655. if (OrigTy->isPointerTy())
  1656. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1657. llvm::Type *Types[] = { Ty };
  1658. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  1659. llvm::Value *Value = Src.getScalarVal();
  1660. if (OrigTy->isPointerTy())
  1661. Value = Builder.CreatePtrToInt(Value, Ty);
  1662. Builder.CreateCall(
  1663. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  1664. }
  1665. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  1666. // generating write-barries API. It is currently a global, ivar,
  1667. // or neither.
  1668. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  1669. LValue &LV,
  1670. bool IsMemberAccess=false) {
  1671. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  1672. return;
  1673. if (isa<ObjCIvarRefExpr>(E)) {
  1674. QualType ExpTy = E->getType();
  1675. if (IsMemberAccess && ExpTy->isPointerType()) {
  1676. // If ivar is a structure pointer, assigning to field of
  1677. // this struct follows gcc's behavior and makes it a non-ivar
  1678. // writer-barrier conservatively.
  1679. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1680. if (ExpTy->isRecordType()) {
  1681. LV.setObjCIvar(false);
  1682. return;
  1683. }
  1684. }
  1685. LV.setObjCIvar(true);
  1686. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  1687. LV.setBaseIvarExp(Exp->getBase());
  1688. LV.setObjCArray(E->getType()->isArrayType());
  1689. return;
  1690. }
  1691. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  1692. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  1693. if (VD->hasGlobalStorage()) {
  1694. LV.setGlobalObjCRef(true);
  1695. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  1696. }
  1697. }
  1698. LV.setObjCArray(E->getType()->isArrayType());
  1699. return;
  1700. }
  1701. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  1702. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1703. return;
  1704. }
  1705. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  1706. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1707. if (LV.isObjCIvar()) {
  1708. // If cast is to a structure pointer, follow gcc's behavior and make it
  1709. // a non-ivar write-barrier.
  1710. QualType ExpTy = E->getType();
  1711. if (ExpTy->isPointerType())
  1712. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1713. if (ExpTy->isRecordType())
  1714. LV.setObjCIvar(false);
  1715. }
  1716. return;
  1717. }
  1718. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  1719. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  1720. return;
  1721. }
  1722. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  1723. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1724. return;
  1725. }
  1726. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  1727. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1728. return;
  1729. }
  1730. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  1731. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1732. return;
  1733. }
  1734. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  1735. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  1736. if (LV.isObjCIvar() && !LV.isObjCArray())
  1737. // Using array syntax to assigning to what an ivar points to is not
  1738. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  1739. LV.setObjCIvar(false);
  1740. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  1741. // Using array syntax to assigning to what global points to is not
  1742. // same as assigning to the global itself. {id *G;} G[i] = 0;
  1743. LV.setGlobalObjCRef(false);
  1744. return;
  1745. }
  1746. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  1747. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  1748. // We don't know if member is an 'ivar', but this flag is looked at
  1749. // only in the context of LV.isObjCIvar().
  1750. LV.setObjCArray(E->getType()->isArrayType());
  1751. return;
  1752. }
  1753. }
  1754. static llvm::Value *
  1755. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  1756. llvm::Value *V, llvm::Type *IRType,
  1757. StringRef Name = StringRef()) {
  1758. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  1759. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  1760. }
  1761. static LValue EmitThreadPrivateVarDeclLValue(
  1762. CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
  1763. llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
  1764. V = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, V, Loc);
  1765. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1766. return CGF.MakeAddrLValue(V, T, Alignment);
  1767. }
  1768. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  1769. const Expr *E, const VarDecl *VD) {
  1770. QualType T = E->getType();
  1771. // If it's thread_local, emit a call to its wrapper function instead.
  1772. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  1773. CGF.CGM.getCXXABI().usesThreadWrapperFunction())
  1774. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  1775. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  1776. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  1777. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1778. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  1779. LValue LV;
  1780. // Emit reference to the private copy of the variable if it is an OpenMP
  1781. // threadprivate variable.
  1782. if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1783. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, V, RealVarTy, Alignment,
  1784. E->getExprLoc());
  1785. if (VD->getType()->isReferenceType()) {
  1786. llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
  1787. LI->setAlignment(Alignment.getQuantity());
  1788. V = LI;
  1789. LV = CGF.MakeNaturalAlignAddrLValue(V, T);
  1790. } else {
  1791. LV = CGF.MakeAddrLValue(V, T, Alignment);
  1792. }
  1793. setObjCGCLValueClass(CGF.getContext(), E, LV);
  1794. return LV;
  1795. }
  1796. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
  1797. const Expr *E, const FunctionDecl *FD) {
  1798. llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
  1799. if (!FD->hasPrototype()) {
  1800. if (const FunctionProtoType *Proto =
  1801. FD->getType()->getAs<FunctionProtoType>()) {
  1802. // Ugly case: for a K&R-style definition, the type of the definition
  1803. // isn't the same as the type of a use. Correct for this with a
  1804. // bitcast.
  1805. QualType NoProtoType =
  1806. CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
  1807. NoProtoType = CGF.getContext().getPointerType(NoProtoType);
  1808. V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
  1809. }
  1810. }
  1811. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  1812. return CGF.MakeAddrLValue(V, E->getType(), Alignment);
  1813. }
  1814. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  1815. llvm::Value *ThisValue) {
  1816. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  1817. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  1818. return CGF.EmitLValueForField(LV, FD);
  1819. }
  1820. /// Named Registers are named metadata pointing to the register name
  1821. /// which will be read from/written to as an argument to the intrinsic
  1822. /// @llvm.read/write_register.
  1823. /// So far, only the name is being passed down, but other options such as
  1824. /// register type, allocation type or even optimization options could be
  1825. /// passed down via the metadata node.
  1826. static LValue EmitGlobalNamedRegister(const VarDecl *VD,
  1827. CodeGenModule &CGM,
  1828. CharUnits Alignment) {
  1829. SmallString<64> Name("llvm.named.register.");
  1830. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  1831. assert(Asm->getLabel().size() < 64-Name.size() &&
  1832. "Register name too big");
  1833. Name.append(Asm->getLabel());
  1834. llvm::NamedMDNode *M =
  1835. CGM.getModule().getOrInsertNamedMetadata(Name);
  1836. if (M->getNumOperands() == 0) {
  1837. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  1838. Asm->getLabel());
  1839. llvm::Metadata *Ops[] = {Str};
  1840. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  1841. }
  1842. return LValue::MakeGlobalReg(
  1843. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)),
  1844. VD->getType(), Alignment);
  1845. }
  1846. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  1847. const NamedDecl *ND = E->getDecl();
  1848. CharUnits Alignment = getContext().getDeclAlign(ND);
  1849. QualType T = E->getType();
  1850. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1851. // Global Named registers access via intrinsics only
  1852. if (VD->getStorageClass() == SC_Register &&
  1853. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  1854. return EmitGlobalNamedRegister(VD, CGM, Alignment);
  1855. // A DeclRefExpr for a reference initialized by a constant expression can
  1856. // appear without being odr-used. Directly emit the constant initializer.
  1857. const Expr *Init = VD->getAnyInitializer(VD);
  1858. if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
  1859. VD->isUsableInConstantExpressions(getContext()) &&
  1860. VD->checkInitIsICE()) {
  1861. llvm::Constant *Val =
  1862. CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
  1863. assert(Val && "failed to emit reference constant expression");
  1864. // FIXME: Eventually we will want to emit vector element references.
  1865. return MakeAddrLValue(Val, T, Alignment);
  1866. }
  1867. // Check for captured variables.
  1868. if (E->refersToEnclosingVariableOrCapture()) {
  1869. if (auto *FD = LambdaCaptureFields.lookup(VD))
  1870. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  1871. else if (CapturedStmtInfo) {
  1872. if (auto *V = LocalDeclMap.lookup(VD))
  1873. return MakeAddrLValue(V, T, Alignment);
  1874. else
  1875. return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  1876. CapturedStmtInfo->getContextValue());
  1877. }
  1878. assert(isa<BlockDecl>(CurCodeDecl));
  1879. return MakeAddrLValue(GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()),
  1880. T, Alignment);
  1881. }
  1882. }
  1883. // FIXME: We should be able to assert this for FunctionDecls as well!
  1884. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  1885. // those with a valid source location.
  1886. assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
  1887. !E->getLocation().isValid()) &&
  1888. "Should not use decl without marking it used!");
  1889. if (ND->hasAttr<WeakRefAttr>()) {
  1890. const auto *VD = cast<ValueDecl>(ND);
  1891. llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
  1892. return MakeAddrLValue(Aliasee, T, Alignment);
  1893. }
  1894. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1895. // Check if this is a global variable.
  1896. if (VD->hasLinkage() || VD->isStaticDataMember())
  1897. return EmitGlobalVarDeclLValue(*this, E, VD);
  1898. bool isBlockVariable = VD->hasAttr<BlocksAttr>();
  1899. llvm::Value *V = LocalDeclMap.lookup(VD);
  1900. if (!V && VD->isStaticLocal())
  1901. V = CGM.getOrCreateStaticVarDecl(
  1902. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
  1903. // Check if variable is threadprivate.
  1904. if (V && getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1905. return EmitThreadPrivateVarDeclLValue(
  1906. *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
  1907. Alignment, E->getExprLoc());
  1908. assert(V && "DeclRefExpr not entered in LocalDeclMap?");
  1909. if (isBlockVariable)
  1910. V = BuildBlockByrefAddress(V, VD);
  1911. LValue LV;
  1912. // HLSL Change Begins
  1913. if (getLangOpts().HLSL) {
  1914. // In hlsl, the referent type is for out parameter.
  1915. // No pointer of pointer temp alloca created for it.
  1916. // So always use V directly.
  1917. LV = MakeAddrLValue(V, T, Alignment);
  1918. } else
  1919. // HLSL Change Ends
  1920. if (VD->getType()->isReferenceType()) {
  1921. llvm::LoadInst *LI = Builder.CreateLoad(V);
  1922. LI->setAlignment(Alignment.getQuantity());
  1923. V = LI;
  1924. LV = MakeNaturalAlignAddrLValue(V, T);
  1925. } else {
  1926. LV = MakeAddrLValue(V, T, Alignment);
  1927. }
  1928. bool isLocalStorage = VD->hasLocalStorage();
  1929. bool NonGCable = isLocalStorage &&
  1930. !VD->getType()->isReferenceType() &&
  1931. !isBlockVariable;
  1932. if (NonGCable) {
  1933. LV.getQuals().removeObjCGCAttr();
  1934. LV.setNonGC(true);
  1935. }
  1936. bool isImpreciseLifetime =
  1937. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  1938. if (isImpreciseLifetime)
  1939. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  1940. setObjCGCLValueClass(getContext(), E, LV);
  1941. return LV;
  1942. }
  1943. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  1944. return EmitFunctionDeclLValue(*this, E, FD);
  1945. llvm_unreachable("Unhandled DeclRefExpr");
  1946. }
  1947. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  1948. // __extension__ doesn't affect lvalue-ness.
  1949. if (E->getOpcode() == UO_Extension)
  1950. return EmitLValue(E->getSubExpr());
  1951. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  1952. switch (E->getOpcode()) {
  1953. default: llvm_unreachable("Unknown unary operator lvalue!");
  1954. case UO_Deref: {
  1955. QualType T = E->getSubExpr()->getType()->getPointeeType();
  1956. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  1957. LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
  1958. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  1959. // We should not generate __weak write barrier on indirect reference
  1960. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  1961. // But, we continue to generate __strong write barrier on indirect write
  1962. // into a pointer to object.
  1963. if (getLangOpts().ObjC1 &&
  1964. getLangOpts().getGC() != LangOptions::NonGC &&
  1965. LV.isObjCWeak())
  1966. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  1967. return LV;
  1968. }
  1969. case UO_Real:
  1970. case UO_Imag: {
  1971. LValue LV = EmitLValue(E->getSubExpr());
  1972. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  1973. llvm::Value *Addr = LV.getAddress();
  1974. // __real is valid on scalars. This is a faster way of testing that.
  1975. // __imag can only produce an rvalue on scalars.
  1976. if (E->getOpcode() == UO_Real &&
  1977. !cast<llvm::PointerType>(Addr->getType())
  1978. ->getElementType()->isStructTy()) {
  1979. assert(E->getSubExpr()->getType()->isArithmeticType());
  1980. return LV;
  1981. }
  1982. assert(E->getSubExpr()->getType()->isAnyComplexType());
  1983. unsigned Idx = E->getOpcode() == UO_Imag;
  1984. return MakeAddrLValue(
  1985. Builder.CreateStructGEP(nullptr, LV.getAddress(), Idx, "idx"), ExprTy);
  1986. }
  1987. case UO_PreInc:
  1988. case UO_PreDec: {
  1989. LValue LV = EmitLValue(E->getSubExpr());
  1990. bool isInc = E->getOpcode() == UO_PreInc;
  1991. if (E->getType()->isAnyComplexType())
  1992. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1993. else
  1994. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1995. return LV;
  1996. }
  1997. }
  1998. }
  1999. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  2000. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  2001. E->getType());
  2002. }
  2003. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  2004. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  2005. E->getType());
  2006. }
  2007. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  2008. auto SL = E->getFunctionName();
  2009. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  2010. StringRef FnName = CurFn->getName();
  2011. if (FnName.startswith("\01"))
  2012. FnName = FnName.substr(1);
  2013. StringRef NameItems[] = {
  2014. PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
  2015. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  2016. if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
  2017. auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str(), 1);
  2018. return MakeAddrLValue(C, E->getType());
  2019. }
  2020. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  2021. return MakeAddrLValue(C, E->getType());
  2022. }
  2023. /// Emit a type description suitable for use by a runtime sanitizer library. The
  2024. /// format of a type descriptor is
  2025. ///
  2026. /// \code
  2027. /// { i16 TypeKind, i16 TypeInfo }
  2028. /// \endcode
  2029. ///
  2030. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  2031. /// integer, 1 for a floating point value, and -1 for anything else.
  2032. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  2033. // Only emit each type's descriptor once.
  2034. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  2035. return C;
  2036. uint16_t TypeKind = -1;
  2037. uint16_t TypeInfo = 0;
  2038. if (T->isIntegerType()) {
  2039. TypeKind = 0;
  2040. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  2041. (T->isSignedIntegerType() ? 1 : 0);
  2042. } else if (T->isFloatingType()) {
  2043. TypeKind = 1;
  2044. TypeInfo = getContext().getTypeSize(T);
  2045. }
  2046. // Format the type name as if for a diagnostic, including quotes and
  2047. // optionally an 'aka'.
  2048. SmallString<32> Buffer;
  2049. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  2050. (intptr_t)T.getAsOpaquePtr(),
  2051. StringRef(), StringRef(), None, Buffer,
  2052. None);
  2053. llvm::Constant *Components[] = {
  2054. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  2055. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  2056. };
  2057. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  2058. auto *GV = new llvm::GlobalVariable(
  2059. CGM.getModule(), Descriptor->getType(),
  2060. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  2061. GV->setUnnamedAddr(true);
  2062. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  2063. // Remember the descriptor for this type.
  2064. CGM.setTypeDescriptorInMap(T, GV);
  2065. return GV;
  2066. }
  2067. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  2068. llvm::Type *TargetTy = IntPtrTy;
  2069. // Floating-point types which fit into intptr_t are bitcast to integers
  2070. // and then passed directly (after zero-extension, if necessary).
  2071. if (V->getType()->isFloatingPointTy()) {
  2072. unsigned Bits = V->getType()->getPrimitiveSizeInBits();
  2073. if (Bits <= TargetTy->getIntegerBitWidth())
  2074. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  2075. Bits));
  2076. }
  2077. // Integers which fit in intptr_t are zero-extended and passed directly.
  2078. if (V->getType()->isIntegerTy() &&
  2079. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2080. return Builder.CreateZExt(V, TargetTy);
  2081. // Pointers are passed directly, everything else is passed by address.
  2082. if (!V->getType()->isPointerTy()) {
  2083. llvm::Value *Ptr = CreateTempAlloca(V->getType());
  2084. Builder.CreateStore(V, Ptr);
  2085. V = Ptr;
  2086. }
  2087. return Builder.CreatePtrToInt(V, TargetTy);
  2088. }
  2089. /// \brief Emit a representation of a SourceLocation for passing to a handler
  2090. /// in a sanitizer runtime library. The format for this data is:
  2091. /// \code
  2092. /// struct SourceLocation {
  2093. /// const char *Filename;
  2094. /// int32_t Line, Column;
  2095. /// };
  2096. /// \endcode
  2097. /// For an invalid SourceLocation, the Filename pointer is null.
  2098. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2099. llvm::Constant *Filename;
  2100. int Line, Column;
  2101. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2102. if (PLoc.isValid()) {
  2103. auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
  2104. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
  2105. Filename = FilenameGV;
  2106. Line = PLoc.getLine();
  2107. Column = PLoc.getColumn();
  2108. } else {
  2109. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2110. Line = Column = 0;
  2111. }
  2112. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2113. Builder.getInt32(Column)};
  2114. return llvm::ConstantStruct::getAnon(Data);
  2115. }
  2116. namespace {
  2117. /// \brief Specify under what conditions this check can be recovered
  2118. enum class CheckRecoverableKind {
  2119. /// Always terminate program execution if this check fails.
  2120. Unrecoverable,
  2121. /// Check supports recovering, runtime has both fatal (noreturn) and
  2122. /// non-fatal handlers for this check.
  2123. Recoverable,
  2124. /// Runtime conditionally aborts, always need to support recovery.
  2125. AlwaysRecoverable
  2126. };
  2127. }
  2128. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2129. assert(llvm::countPopulation(Kind) == 1);
  2130. switch (Kind) {
  2131. case SanitizerKind::Vptr:
  2132. return CheckRecoverableKind::AlwaysRecoverable;
  2133. case SanitizerKind::Return:
  2134. case SanitizerKind::Unreachable:
  2135. return CheckRecoverableKind::Unrecoverable;
  2136. default:
  2137. return CheckRecoverableKind::Recoverable;
  2138. }
  2139. }
  2140. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2141. llvm::FunctionType *FnType,
  2142. ArrayRef<llvm::Value *> FnArgs,
  2143. StringRef CheckName,
  2144. CheckRecoverableKind RecoverKind, bool IsFatal,
  2145. llvm::BasicBlock *ContBB) {
  2146. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2147. bool NeedsAbortSuffix =
  2148. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2149. std::string FnName = ("__ubsan_handle_" + CheckName +
  2150. (NeedsAbortSuffix ? "_abort" : "")).str();
  2151. bool MayReturn =
  2152. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2153. llvm::AttrBuilder B;
  2154. if (!MayReturn) {
  2155. B.addAttribute(llvm::Attribute::NoReturn)
  2156. .addAttribute(llvm::Attribute::NoUnwind);
  2157. }
  2158. B.addAttribute(llvm::Attribute::UWTable);
  2159. llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
  2160. FnType, FnName,
  2161. llvm::AttributeSet::get(CGF.getLLVMContext(),
  2162. llvm::AttributeSet::FunctionIndex, B));
  2163. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2164. if (!MayReturn) {
  2165. HandlerCall->setDoesNotReturn();
  2166. CGF.Builder.CreateUnreachable();
  2167. } else {
  2168. CGF.Builder.CreateBr(ContBB);
  2169. }
  2170. }
  2171. void CodeGenFunction::EmitCheck(
  2172. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2173. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2174. ArrayRef<llvm::Value *> DynamicArgs) {
  2175. assert(IsSanitizerScope);
  2176. assert(Checked.size() > 0);
  2177. llvm::Value *FatalCond = nullptr;
  2178. llvm::Value *RecoverableCond = nullptr;
  2179. llvm::Value *TrapCond = nullptr;
  2180. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2181. llvm::Value *Check = Checked[i].first;
  2182. // -fsanitize-trap= overrides -fsanitize-recover=.
  2183. llvm::Value *&Cond =
  2184. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2185. ? TrapCond
  2186. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2187. ? RecoverableCond
  2188. : FatalCond;
  2189. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2190. }
  2191. if (TrapCond)
  2192. EmitTrapCheck(TrapCond);
  2193. if (!FatalCond && !RecoverableCond)
  2194. return;
  2195. llvm::Value *JointCond;
  2196. if (FatalCond && RecoverableCond)
  2197. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2198. else
  2199. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2200. assert(JointCond);
  2201. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2202. assert(SanOpts.has(Checked[0].second));
  2203. #ifndef NDEBUG
  2204. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2205. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2206. "All recoverable kinds in a single check must be same!");
  2207. assert(SanOpts.has(Checked[i].second));
  2208. }
  2209. #endif
  2210. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2211. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2212. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2213. // Give hint that we very much don't expect to execute the handler
  2214. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2215. llvm::MDBuilder MDHelper(getLLVMContext());
  2216. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2217. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2218. EmitBlock(Handlers);
  2219. // Emit handler arguments and create handler function type.
  2220. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2221. auto *InfoPtr =
  2222. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2223. llvm::GlobalVariable::PrivateLinkage, Info);
  2224. InfoPtr->setUnnamedAddr(true);
  2225. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2226. SmallVector<llvm::Value *, 4> Args;
  2227. SmallVector<llvm::Type *, 4> ArgTypes;
  2228. Args.reserve(DynamicArgs.size() + 1);
  2229. ArgTypes.reserve(DynamicArgs.size() + 1);
  2230. // Handler functions take an i8* pointing to the (handler-specific) static
  2231. // information block, followed by a sequence of intptr_t arguments
  2232. // representing operand values.
  2233. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2234. ArgTypes.push_back(Int8PtrTy);
  2235. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2236. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2237. ArgTypes.push_back(IntPtrTy);
  2238. }
  2239. llvm::FunctionType *FnType =
  2240. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2241. if (!FatalCond || !RecoverableCond) {
  2242. // Simple case: we need to generate a single handler call, either
  2243. // fatal, or non-fatal.
  2244. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
  2245. (FatalCond != nullptr), Cont);
  2246. } else {
  2247. // Emit two handler calls: first one for set of unrecoverable checks,
  2248. // another one for recoverable.
  2249. llvm::BasicBlock *NonFatalHandlerBB =
  2250. createBasicBlock("non_fatal." + CheckName);
  2251. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2252. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2253. EmitBlock(FatalHandlerBB);
  2254. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
  2255. NonFatalHandlerBB);
  2256. EmitBlock(NonFatalHandlerBB);
  2257. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
  2258. Cont);
  2259. }
  2260. EmitBlock(Cont);
  2261. }
  2262. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
  2263. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2264. // If we're optimizing, collapse all calls to trap down to just one per
  2265. // function to save on code size.
  2266. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  2267. TrapBB = createBasicBlock("trap");
  2268. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2269. EmitBlock(TrapBB);
  2270. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2271. TrapCall->setDoesNotReturn();
  2272. TrapCall->setDoesNotThrow();
  2273. Builder.CreateUnreachable();
  2274. } else {
  2275. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2276. }
  2277. EmitBlock(Cont);
  2278. }
  2279. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  2280. llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
  2281. if (!CGM.getCodeGenOpts().TrapFuncName.empty())
  2282. TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
  2283. "trap-func-name",
  2284. CGM.getCodeGenOpts().TrapFuncName);
  2285. return TrapCall;
  2286. }
  2287. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  2288. /// array to pointer, return the array subexpression.
  2289. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  2290. // If this isn't just an array->pointer decay, bail out.
  2291. const auto *CE = dyn_cast<CastExpr>(E);
  2292. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  2293. return nullptr;
  2294. // If this is a decay from variable width array, bail out.
  2295. const Expr *SubExpr = CE->getSubExpr();
  2296. if (SubExpr->getType()->isVariableArrayType())
  2297. return nullptr;
  2298. return SubExpr;
  2299. }
  2300. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2301. bool Accessed) {
  2302. // The index must always be an integer, which is not an aggregate. Emit it.
  2303. llvm::Value *Idx = EmitScalarExpr(E->getIdx());
  2304. QualType IdxTy = E->getIdx()->getType();
  2305. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  2306. if (SanOpts.has(SanitizerKind::ArrayBounds))
  2307. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  2308. // If the base is a vector type, then we are forming a vector element lvalue
  2309. // with this subscript.
  2310. if (E->getBase()->getType()->isVectorType() &&
  2311. !isa<ExtVectorElementExpr>(E->getBase())) {
  2312. // Emit the vector as an lvalue to get its address.
  2313. LValue LHS = EmitLValue(E->getBase());
  2314. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  2315. return LValue::MakeVectorElt(LHS.getAddress(), Idx,
  2316. E->getBase()->getType(), LHS.getAlignment());
  2317. }
  2318. // Extend or truncate the index type to 32 or 64-bits.
  2319. if (Idx->getType() != IntPtrTy)
  2320. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  2321. // HLSL Change Starts
  2322. const Expr *Array = isSimpleArrayDecayOperand(E->getBase());
  2323. assert((!getLangOpts().HLSL || nullptr == Array) &&
  2324. "else array decay snuck in AST for HLSL");
  2325. // HLSL Change Ends
  2326. // We know that the pointer points to a type of the correct size, unless the
  2327. // size is a VLA or Objective-C interface.
  2328. llvm::Value *Address = nullptr;
  2329. CharUnits ArrayAlignment;
  2330. if (isa<ExtVectorElementExpr>(E->getBase())) {
  2331. LValue LV = EmitLValue(E->getBase());
  2332. Address = EmitExtVectorElementLValue(LV);
  2333. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2334. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  2335. QualType EQT = ExprVT->getElementType();
  2336. return MakeAddrLValue(Address, EQT,
  2337. getContext().getTypeAlignInChars(EQT));
  2338. }
  2339. else if (const VariableArrayType *vla =
  2340. getContext().getAsVariableArrayType(E->getType())) {
  2341. // The base must be a pointer, which is not an aggregate. Emit
  2342. // it. It needs to be emitted first in case it's what captures
  2343. // the VLA bounds.
  2344. Address = EmitScalarExpr(E->getBase());
  2345. // The element count here is the total number of non-VLA elements.
  2346. llvm::Value *numElements = getVLASize(vla).first;
  2347. // Effectively, the multiply by the VLA size is part of the GEP.
  2348. // GEP indexes are signed, and scaling an index isn't permitted to
  2349. // signed-overflow, so we use the same semantics for our explicit
  2350. // multiply. We suppress this if overflow is not undefined behavior.
  2351. if (getLangOpts().isSignedOverflowDefined()) {
  2352. Idx = Builder.CreateMul(Idx, numElements);
  2353. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2354. } else {
  2355. Idx = Builder.CreateNSWMul(Idx, numElements);
  2356. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2357. }
  2358. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  2359. // Indexing over an interface, as in "NSString *P; P[4];"
  2360. llvm::Value *InterfaceSize =
  2361. llvm::ConstantInt::get(Idx->getType(),
  2362. getContext().getTypeSizeInChars(OIT).getQuantity());
  2363. Idx = Builder.CreateMul(Idx, InterfaceSize);
  2364. // The base must be a pointer, which is not an aggregate. Emit it.
  2365. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2366. Address = EmitCastToVoidPtr(Base);
  2367. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2368. Address = Builder.CreateBitCast(Address, Base->getType());
  2369. } else if (!getLangOpts().HLSL && Array) { // HLSL Change - No Array to pointer decay for HLSL
  2370. // If this is A[i] where A is an array, the frontend will have decayed the
  2371. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  2372. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  2373. // "gep x, i" here. Emit one "gep A, 0, i".
  2374. assert(Array->getType()->isArrayType() &&
  2375. "Array to pointer decay must have array source type!");
  2376. LValue ArrayLV;
  2377. // For simple multidimensional array indexing, set the 'accessed' flag for
  2378. // better bounds-checking of the base expression.
  2379. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  2380. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2381. else
  2382. ArrayLV = EmitLValue(Array);
  2383. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2384. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2385. llvm::Value *Args[] = { Zero, Idx };
  2386. // Propagate the alignment from the array itself to the result.
  2387. ArrayAlignment = ArrayLV.getAlignment();
  2388. if (getLangOpts().isSignedOverflowDefined())
  2389. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2390. else
  2391. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2392. } else {
  2393. // HLSL Change Starts
  2394. const ArrayType *AT = dyn_cast<ArrayType>(E->getBase()->getType()->getCanonicalTypeUnqualified());
  2395. if (getContext().getLangOpts().HLSL && AT) {
  2396. LValue ArrayLV;
  2397. // For simple multidimensional array indexing, set the 'accessed' flag for
  2398. // better bounds-checking of the base expression.
  2399. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E->getBase()))
  2400. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2401. else
  2402. ArrayLV = EmitLValue(E->getBase());
  2403. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2404. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2405. llvm::Value *Args[] = { Zero, Idx };
  2406. // Propagate the alignment from the array itself to the result.
  2407. ArrayAlignment = ArrayLV.getAlignment();
  2408. if (getLangOpts().isSignedOverflowDefined())
  2409. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2410. else
  2411. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2412. } else {
  2413. // HLSL Change Ends
  2414. // The base must be a pointer, which is not an aggregate. Emit it.
  2415. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2416. if (getLangOpts().isSignedOverflowDefined())
  2417. Address = Builder.CreateGEP(Base, Idx, "arrayidx");
  2418. else
  2419. Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
  2420. } // HLSL Change
  2421. }
  2422. QualType T = E->getBase()->getType()->getPointeeType();
  2423. // HLSL Change Starts
  2424. if (getContext().getLangOpts().HLSL && T.isNull()) {
  2425. T = QualType(E->getBase()->getType()->getArrayElementTypeNoTypeQual(), 0);
  2426. }
  2427. // HLSL Change Ends
  2428. assert(!T.isNull() &&
  2429. "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
  2430. // Limit the alignment to that of the result type.
  2431. LValue LV;
  2432. if (!ArrayAlignment.isZero()) {
  2433. CharUnits Align = getContext().getTypeAlignInChars(T);
  2434. ArrayAlignment = std::min(Align, ArrayAlignment);
  2435. LV = MakeAddrLValue(Address, T, ArrayAlignment);
  2436. } else {
  2437. LV = MakeNaturalAlignAddrLValue(Address, T);
  2438. }
  2439. LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
  2440. if (getLangOpts().ObjC1 &&
  2441. getLangOpts().getGC() != LangOptions::NonGC) {
  2442. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2443. setObjCGCLValueClass(getContext(), E, LV);
  2444. }
  2445. return LV;
  2446. }
  2447. static
  2448. llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
  2449. SmallVectorImpl<unsigned> &Elts) {
  2450. SmallVector<llvm::Constant*, 4> CElts;
  2451. for (unsigned i = 0, e = Elts.size(); i != e; ++i)
  2452. CElts.push_back(Builder.getInt32(Elts[i]));
  2453. return llvm::ConstantVector::get(CElts);
  2454. }
  2455. LValue CodeGenFunction::
  2456. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  2457. // Emit the base vector as an l-value.
  2458. LValue Base;
  2459. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2460. if (E->isArrow()) {
  2461. // If it is a pointer to a vector, emit the address and form an lvalue with
  2462. // it.
  2463. llvm::Value *Ptr = EmitScalarExpr(E->getBase());
  2464. const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
  2465. Base = MakeAddrLValue(Ptr, PT->getPointeeType());
  2466. Base.getQuals().removeObjCGCAttr();
  2467. } else if (E->getBase()->isGLValue()) {
  2468. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2469. // emit the base as an lvalue.
  2470. assert(E->getBase()->getType()->isVectorType());
  2471. Base = EmitLValue(E->getBase());
  2472. } else {
  2473. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2474. assert(E->getBase()->getType()->isVectorType() &&
  2475. "Result must be a vector");
  2476. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2477. // Store the vector to memory (because LValue wants an address).
  2478. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2479. Builder.CreateStore(Vec, VecMem);
  2480. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2481. }
  2482. QualType type =
  2483. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2484. // Encode the element access list into a vector of unsigned indices.
  2485. SmallVector<unsigned, 4> Indices;
  2486. E->getEncodedElementAccess(Indices);
  2487. if (Base.isSimple()) {
  2488. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2489. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2490. Base.getAlignment());
  2491. }
  2492. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2493. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2494. SmallVector<llvm::Constant *, 4> CElts;
  2495. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2496. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2497. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2498. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2499. Base.getAlignment());
  2500. }
  2501. // HLSL Change Starts
  2502. LValue
  2503. CodeGenFunction::EmitExtMatrixElementExpr(const ExtMatrixElementExpr *E) {
  2504. LValue Base;
  2505. assert(!E->isArrow() && "ExtMatrixElementExpr's base will not be Arrow");
  2506. if (E->getBase()->isGLValue()) {
  2507. // if the base is an lvalue ( as in the case of foo.x.x),
  2508. // emit the base as an lvalue.
  2509. const Expr *base = E->getBase();
  2510. assert(hlsl::IsHLSLMatType(base->getType()));
  2511. Base = EmitLValue(base);
  2512. } else {
  2513. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2514. assert(hlsl::IsHLSLMatType(E->getBase()->getType()) &&
  2515. "Result must be a vector");
  2516. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2517. // Store the vector to memory (because LValue wants an address).
  2518. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2519. CGM.getHLSLRuntime().EmitHLSLMatrixStore(*this, Vec, VecMem, E->getBase()->getType());
  2520. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2521. }
  2522. // Encode the element access list into a vector of unsigned indices.
  2523. SmallVector<unsigned, 4> Indices;
  2524. E->getEncodedElementAccess(Indices);
  2525. llvm::Type *ResultTy =
  2526. ConvertType(getContext().getLValueReferenceType(E->getType()));
  2527. llvm::Value *matBase = nullptr;
  2528. llvm::Constant *CV = nullptr;
  2529. if (Base.isSimple()) {
  2530. SmallVector<llvm::Constant *, 4> CElts;
  2531. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2532. CElts.push_back(Builder.getInt32(Indices[i]));
  2533. CV = llvm::ConstantVector::get(CElts);
  2534. matBase = Base.getAddress();
  2535. } else {
  2536. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2537. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2538. SmallVector<llvm::Constant *, 4> CElts;
  2539. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2540. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2541. CV = llvm::ConstantVector::get(CElts);
  2542. matBase = Base.getExtVectorAddr();
  2543. }
  2544. llvm::Value *Result = CGM.getHLSLRuntime().EmitHLSLMatrixElement(
  2545. *this, ResultTy, {matBase, CV}, E->getBase()->getType());
  2546. return MakeAddrLValue(Result, E->getType());
  2547. }
  2548. LValue
  2549. CodeGenFunction::EmitHLSLVectorElementExpr(const HLSLVectorElementExpr *E) {
  2550. // Emit the base vector as an l-value.
  2551. // Clone EmitExtVectorElementExpr for now
  2552. // TODO: difference between ExtVector and HlslVector
  2553. LValue Base;
  2554. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2555. if (E->isArrow()) {
  2556. // If it is a pointer to a vector, emit the address and form an lvalue with
  2557. // it.
  2558. assert(!getLangOpts().HLSL && "this will not happen for hlsl");
  2559. } else if (E->getBase()->isGLValue()) {
  2560. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2561. // emit the base as an lvalue.
  2562. const Expr *base = E->getBase();
  2563. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(base)) {
  2564. if (ICE->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  2565. E->getNumElements() == 1) {
  2566. // For pattern like:
  2567. // static bool t;
  2568. // t.x = bool(a);
  2569. // Just ignore the .x, treat it like t = bool(a);
  2570. return EmitLValue(ICE->getSubExpr());
  2571. }
  2572. }
  2573. assert(hlsl::IsHLSLVecType(base->getType()));
  2574. Base = EmitLValue(base);
  2575. } else {
  2576. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2577. assert(hlsl::IsHLSLVecType(E->getBase()->getType()) &&
  2578. "Result must be a vector");
  2579. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2580. Vec = EmitToMemory(Vec, E->getBase()->getType());
  2581. // Store the vector to memory (because LValue wants an address).
  2582. llvm::Value *VecMemPtr = CreateMemTemp(E->getBase()->getType());
  2583. Builder.CreateStore(Vec, VecMemPtr);
  2584. Base = MakeAddrLValue(VecMemPtr, E->getBase()->getType());
  2585. }
  2586. QualType type =
  2587. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2588. // Encode the element access list into a vector of unsigned indices.
  2589. SmallVector<unsigned, 4> Indices;
  2590. E->getEncodedElementAccess(Indices);
  2591. if (Base.isSimple()) {
  2592. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2593. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2594. Base.getAlignment());
  2595. }
  2596. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2597. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2598. SmallVector<llvm::Constant *, 4> CElts;
  2599. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2600. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2601. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2602. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2603. Base.getAlignment());
  2604. }
  2605. // HLSL Change Ends
  2606. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  2607. Expr *BaseExpr = E->getBase();
  2608. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  2609. LValue BaseLV;
  2610. if (E->isArrow()) {
  2611. llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
  2612. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  2613. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
  2614. BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
  2615. } else
  2616. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  2617. NamedDecl *ND = E->getMemberDecl();
  2618. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  2619. LValue LV = EmitLValueForField(BaseLV, Field);
  2620. setObjCGCLValueClass(getContext(), E, LV);
  2621. return LV;
  2622. }
  2623. if (auto *VD = dyn_cast<VarDecl>(ND))
  2624. return EmitGlobalVarDeclLValue(*this, E, VD);
  2625. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2626. return EmitFunctionDeclLValue(*this, E, FD);
  2627. llvm_unreachable("Unhandled member declaration!");
  2628. }
  2629. /// Given that we are currently emitting a lambda, emit an l-value for
  2630. /// one of its members.
  2631. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  2632. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  2633. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  2634. QualType LambdaTagType =
  2635. getContext().getTagDeclType(Field->getParent());
  2636. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  2637. return EmitLValueForField(LambdaLV, Field);
  2638. }
  2639. LValue CodeGenFunction::EmitLValueForField(LValue base,
  2640. const FieldDecl *field) {
  2641. if (field->isBitField()) {
  2642. const CGRecordLayout &RL =
  2643. CGM.getTypes().getCGRecordLayout(field->getParent());
  2644. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  2645. llvm::Value *Addr = base.getAddress();
  2646. unsigned Idx = RL.getLLVMFieldNo(field);
  2647. if (Idx != 0)
  2648. // For structs, we GEP to the field that the record layout suggests.
  2649. Addr = Builder.CreateStructGEP(nullptr, Addr, Idx, field->getName());
  2650. // Get the access type.
  2651. llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
  2652. getLLVMContext(), Info.StorageSize,
  2653. CGM.getContext().getTargetAddressSpace(base.getType()));
  2654. if (Addr->getType() != PtrTy)
  2655. Addr = Builder.CreateBitCast(Addr, PtrTy);
  2656. QualType fieldType =
  2657. field->getType().withCVRQualifiers(base.getVRQualifiers());
  2658. return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
  2659. }
  2660. const RecordDecl *rec = field->getParent();
  2661. QualType type = field->getType();
  2662. CharUnits alignment = getContext().getDeclAlign(field);
  2663. // FIXME: It should be impossible to have an LValue without alignment for a
  2664. // complete type.
  2665. if (!base.getAlignment().isZero())
  2666. alignment = std::min(alignment, base.getAlignment());
  2667. bool mayAlias = rec->hasAttr<MayAliasAttr>();
  2668. llvm::Value *addr = base.getAddress();
  2669. unsigned cvr = base.getVRQualifiers();
  2670. bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
  2671. if (rec->isUnion()) {
  2672. // For unions, there is no pointer adjustment.
  2673. assert(!type->isReferenceType() && "union has reference member");
  2674. // TODO: handle path-aware TBAA for union.
  2675. TBAAPath = false;
  2676. } else {
  2677. // For structs, we GEP to the field that the record layout suggests.
  2678. unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  2679. addr = Builder.CreateStructGEP(nullptr, addr, idx, field->getName());
  2680. // If this is a reference field, load the reference right now.
  2681. if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
  2682. llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
  2683. if (cvr & Qualifiers::Volatile) load->setVolatile(true);
  2684. load->setAlignment(alignment.getQuantity());
  2685. // Loading the reference will disable path-aware TBAA.
  2686. TBAAPath = false;
  2687. if (CGM.shouldUseTBAA()) {
  2688. llvm::MDNode *tbaa;
  2689. if (mayAlias)
  2690. tbaa = CGM.getTBAAInfo(getContext().CharTy);
  2691. else
  2692. tbaa = CGM.getTBAAInfo(type);
  2693. if (tbaa)
  2694. CGM.DecorateInstruction(load, tbaa);
  2695. }
  2696. addr = load;
  2697. mayAlias = false;
  2698. type = refType->getPointeeType();
  2699. if (type->isIncompleteType())
  2700. alignment = CharUnits();
  2701. else
  2702. alignment = getContext().getTypeAlignInChars(type);
  2703. cvr = 0; // qualifiers don't recursively apply to referencee
  2704. }
  2705. }
  2706. // Make sure that the address is pointing to the right type. This is critical
  2707. // for both unions and structs. A union needs a bitcast, a struct element
  2708. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2709. // type.
  2710. addr = EmitBitCastOfLValueToProperType(*this, addr,
  2711. CGM.getTypes().ConvertTypeForMem(type),
  2712. field->getName());
  2713. if (field->hasAttr<AnnotateAttr>())
  2714. addr = EmitFieldAnnotations(field, addr);
  2715. LValue LV = MakeAddrLValue(addr, type, alignment);
  2716. LV.getQuals().addCVRQualifiers(cvr);
  2717. if (TBAAPath) {
  2718. const ASTRecordLayout &Layout =
  2719. getContext().getASTRecordLayout(field->getParent());
  2720. // Set the base type to be the base type of the base LValue and
  2721. // update offset to be relative to the base type.
  2722. LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
  2723. LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
  2724. Layout.getFieldOffset(field->getFieldIndex()) /
  2725. getContext().getCharWidth());
  2726. }
  2727. // __weak attribute on a field is ignored.
  2728. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  2729. LV.getQuals().removeObjCGCAttr();
  2730. // Fields of may_alias structs act like 'char' for TBAA purposes.
  2731. // FIXME: this should get propagated down through anonymous structs
  2732. // and unions.
  2733. if (mayAlias && LV.getTBAAInfo())
  2734. LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
  2735. return LV;
  2736. }
  2737. LValue
  2738. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  2739. const FieldDecl *Field) {
  2740. QualType FieldType = Field->getType();
  2741. if (!FieldType->isReferenceType())
  2742. return EmitLValueForField(Base, Field);
  2743. const CGRecordLayout &RL =
  2744. CGM.getTypes().getCGRecordLayout(Field->getParent());
  2745. unsigned idx = RL.getLLVMFieldNo(Field);
  2746. llvm::Value *V = Builder.CreateStructGEP(nullptr, Base.getAddress(), idx);
  2747. assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
  2748. // Make sure that the address is pointing to the right type. This is critical
  2749. // for both unions and structs. A union needs a bitcast, a struct element
  2750. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2751. // type.
  2752. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  2753. V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
  2754. CharUnits Alignment = getContext().getDeclAlign(Field);
  2755. // FIXME: It should be impossible to have an LValue without alignment for a
  2756. // complete type.
  2757. if (!Base.getAlignment().isZero())
  2758. Alignment = std::min(Alignment, Base.getAlignment());
  2759. return MakeAddrLValue(V, FieldType, Alignment);
  2760. }
  2761. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  2762. if (E->isFileScope()) {
  2763. llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  2764. return MakeAddrLValue(GlobalPtr, E->getType());
  2765. }
  2766. if (E->getType()->isVariablyModifiedType())
  2767. // make sure to emit the VLA size.
  2768. EmitVariablyModifiedType(E->getType());
  2769. llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  2770. const Expr *InitExpr = E->getInitializer();
  2771. LValue Result = MakeAddrLValue(DeclPtr, E->getType());
  2772. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  2773. /*Init*/ true);
  2774. return Result;
  2775. }
  2776. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  2777. if (!E->isGLValue())
  2778. // Initializing an aggregate temporary in C++11: T{...}.
  2779. return EmitAggExprToLValue(E);
  2780. // An lvalue initializer list must be initializing a reference.
  2781. assert(E->getNumInits() == 1 && "reference init with multiple values");
  2782. return EmitLValue(E->getInit(0));
  2783. }
  2784. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  2785. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  2786. /// LValue is returned and the current block has been terminated.
  2787. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  2788. const Expr *Operand) {
  2789. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  2790. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  2791. return None;
  2792. }
  2793. return CGF.EmitLValue(Operand);
  2794. }
  2795. LValue CodeGenFunction::
  2796. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  2797. if (!expr->isGLValue()) {
  2798. // ?: here should be an aggregate.
  2799. assert(hasAggregateEvaluationKind(expr->getType()) &&
  2800. "Unexpected conditional operator!");
  2801. return EmitAggExprToLValue(expr);
  2802. }
  2803. OpaqueValueMapping binding(*this, expr);
  2804. const Expr *condExpr = expr->getCond();
  2805. bool CondExprBool;
  2806. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  2807. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  2808. if (!CondExprBool) std::swap(live, dead);
  2809. if (!ContainsLabel(dead)) {
  2810. // If the true case is live, we need to track its region.
  2811. if (CondExprBool)
  2812. incrementProfileCounter(expr);
  2813. return EmitLValue(live);
  2814. }
  2815. }
  2816. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  2817. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  2818. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  2819. ConditionalEvaluation eval(*this);
  2820. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  2821. // Any temporaries created here are conditional.
  2822. EmitBlock(lhsBlock);
  2823. incrementProfileCounter(expr);
  2824. eval.begin(*this);
  2825. Optional<LValue> lhs =
  2826. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  2827. eval.end(*this);
  2828. if (lhs && !lhs->isSimple())
  2829. return EmitUnsupportedLValue(expr, "conditional operator");
  2830. lhsBlock = Builder.GetInsertBlock();
  2831. if (lhs)
  2832. Builder.CreateBr(contBlock);
  2833. // Any temporaries created here are conditional.
  2834. EmitBlock(rhsBlock);
  2835. eval.begin(*this);
  2836. Optional<LValue> rhs =
  2837. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  2838. eval.end(*this);
  2839. if (rhs && !rhs->isSimple())
  2840. return EmitUnsupportedLValue(expr, "conditional operator");
  2841. rhsBlock = Builder.GetInsertBlock();
  2842. EmitBlock(contBlock);
  2843. if (lhs && rhs) {
  2844. llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
  2845. 2, "cond-lvalue");
  2846. phi->addIncoming(lhs->getAddress(), lhsBlock);
  2847. phi->addIncoming(rhs->getAddress(), rhsBlock);
  2848. return MakeAddrLValue(phi, expr->getType());
  2849. } else {
  2850. assert((lhs || rhs) &&
  2851. "both operands of glvalue conditional are throw-expressions?");
  2852. return lhs ? *lhs : *rhs;
  2853. }
  2854. }
  2855. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  2856. /// type. If the cast is to a reference, we can have the usual lvalue result,
  2857. /// otherwise if a cast is needed by the code generator in an lvalue context,
  2858. /// then it must mean that we need the address of an aggregate in order to
  2859. /// access one of its members. This can happen for all the reasons that casts
  2860. /// are permitted with aggregate result, including noop aggregate casts, and
  2861. /// cast from scalar to union.
  2862. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  2863. // HLSL Change Begins
  2864. if (hlsl::IsHLSLMatType(E->getType()) || hlsl::IsHLSLMatType(E->getSubExpr()->getType())) {
  2865. LValue LV = EmitLValue(E->getSubExpr());
  2866. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2867. llvm::Type *RetTy = ConvertType(ToType);
  2868. // type not changed, LValueToRValue, CStyleCast may go this path
  2869. if (LV.getAddress()->getType() == RetTy)
  2870. return LV;
  2871. llvm::Value *cast = CGM.getHLSLRuntime().EmitHLSLMatrixOperationCall(*this, E, RetTy, { LV.getAddress() });
  2872. return MakeAddrLValue(cast, ToType);
  2873. }
  2874. // HLSL Change Ends
  2875. switch (E->getCastKind()) {
  2876. case CK_ToVoid:
  2877. case CK_BitCast:
  2878. case CK_ArrayToPointerDecay:
  2879. case CK_FunctionToPointerDecay:
  2880. case CK_NullToMemberPointer:
  2881. case CK_NullToPointer:
  2882. case CK_IntegralToPointer:
  2883. case CK_PointerToIntegral:
  2884. case CK_PointerToBoolean:
  2885. case CK_VectorSplat:
  2886. case CK_IntegralCast:
  2887. case CK_IntegralToBoolean:
  2888. case CK_IntegralToFloating:
  2889. case CK_FloatingToIntegral:
  2890. case CK_FloatingToBoolean:
  2891. case CK_FloatingCast:
  2892. case CK_FloatingRealToComplex:
  2893. case CK_FloatingComplexToReal:
  2894. case CK_FloatingComplexToBoolean:
  2895. case CK_FloatingComplexCast:
  2896. case CK_FloatingComplexToIntegralComplex:
  2897. case CK_IntegralRealToComplex:
  2898. case CK_IntegralComplexToReal:
  2899. case CK_IntegralComplexToBoolean:
  2900. case CK_IntegralComplexCast:
  2901. case CK_IntegralComplexToFloatingComplex:
  2902. case CK_DerivedToBaseMemberPointer:
  2903. case CK_BaseToDerivedMemberPointer:
  2904. case CK_MemberPointerToBoolean:
  2905. case CK_ReinterpretMemberPointer:
  2906. case CK_AnyPointerToBlockPointerCast:
  2907. case CK_ARCProduceObject:
  2908. case CK_ARCConsumeObject:
  2909. case CK_ARCReclaimReturnedObject:
  2910. case CK_ARCExtendBlockObject:
  2911. case CK_CopyAndAutoreleaseBlockObject:
  2912. case CK_AddressSpaceConversion:
  2913. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  2914. case CK_Dependent:
  2915. llvm_unreachable("dependent cast kind in IR gen!");
  2916. case CK_BuiltinFnToFnPtr:
  2917. llvm_unreachable("builtin functions are handled elsewhere");
  2918. // These are never l-values; just use the aggregate emission code.
  2919. case CK_NonAtomicToAtomic:
  2920. case CK_AtomicToNonAtomic:
  2921. return EmitAggExprToLValue(E);
  2922. case CK_Dynamic: {
  2923. LValue LV = EmitLValue(E->getSubExpr());
  2924. llvm::Value *V = LV.getAddress();
  2925. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  2926. return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  2927. }
  2928. case CK_ConstructorConversion:
  2929. case CK_UserDefinedConversion:
  2930. case CK_CPointerToObjCPointerCast:
  2931. case CK_BlockPointerToObjCPointerCast:
  2932. case CK_NoOp:
  2933. case CK_LValueToRValue:
  2934. return EmitLValue(E->getSubExpr());
  2935. case CK_UncheckedDerivedToBase:
  2936. case CK_DerivedToBase: {
  2937. const RecordType *DerivedClassTy =
  2938. E->getSubExpr()->getType()->getAs<RecordType>();
  2939. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2940. LValue LV = EmitLValue(E->getSubExpr());
  2941. llvm::Value *This = LV.getAddress();
  2942. // Perform the derived-to-base conversion
  2943. llvm::Value *Base = GetAddressOfBaseClass(
  2944. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  2945. /*NullCheckValue=*/false, E->getExprLoc());
  2946. return MakeAddrLValue(Base, E->getType());
  2947. }
  2948. case CK_ToUnion:
  2949. return EmitAggExprToLValue(E);
  2950. case CK_BaseToDerived: {
  2951. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  2952. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2953. LValue LV = EmitLValue(E->getSubExpr());
  2954. // Perform the base-to-derived conversion
  2955. llvm::Value *Derived =
  2956. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  2957. E->path_begin(), E->path_end(),
  2958. /*NullCheckValue=*/false);
  2959. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  2960. // performed and the object is not of the derived type.
  2961. if (sanitizePerformTypeCheck())
  2962. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  2963. Derived, E->getType());
  2964. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  2965. EmitVTablePtrCheckForCast(E->getType(), Derived, /*MayBeNull=*/false,
  2966. CFITCK_DerivedCast, E->getLocStart());
  2967. return MakeAddrLValue(Derived, E->getType());
  2968. }
  2969. case CK_LValueBitCast: {
  2970. // This must be a reinterpret_cast (or c-style equivalent).
  2971. const auto *CE = cast<ExplicitCastExpr>(E);
  2972. LValue LV = EmitLValue(E->getSubExpr());
  2973. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2974. ConvertType(CE->getTypeAsWritten()));
  2975. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  2976. EmitVTablePtrCheckForCast(E->getType(), V, /*MayBeNull=*/false,
  2977. CFITCK_UnrelatedCast, E->getLocStart());
  2978. return MakeAddrLValue(V, E->getType());
  2979. }
  2980. case CK_ObjCObjectLValueCast: {
  2981. LValue LV = EmitLValue(E->getSubExpr());
  2982. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2983. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2984. ConvertType(ToType));
  2985. return MakeAddrLValue(V, E->getType());
  2986. }
  2987. // HLSL Change Starts
  2988. case CK_HLSLVectorSplat: {
  2989. LValue LV = EmitLValue(E->getSubExpr());
  2990. llvm::Value *LVal = nullptr;
  2991. if (LV.isSimple())
  2992. LVal = LV.getAddress();
  2993. else if (LV.isExtVectorElt()) {
  2994. llvm::Constant *VecElts = LV.getExtVectorElts();
  2995. LVal = Builder.CreateGEP(
  2996. LV.getExtVectorAddr(),
  2997. {Builder.getInt32(0), VecElts->getAggregateElement((unsigned)0)});
  2998. } else
  2999. // TODO: make sure all cases are supported.
  3000. assert(0 && "not implement cases");
  3001. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3002. // bitcast to target type
  3003. llvm::Type *ResultType = ConvertType(ToType);
  3004. llvm::Value *bitcast = Builder.CreateBitCast(LVal, ResultType);
  3005. return MakeAddrLValue(bitcast, ToType);
  3006. }
  3007. case CK_HLSLVectorTruncationCast: {
  3008. LValue LV = EmitLValue(E->getSubExpr());
  3009. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3010. // bitcast to target type
  3011. llvm::Type *ResultType = ConvertType(ToType);
  3012. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  3013. return MakeAddrLValue(bitcast, ToType);
  3014. }
  3015. case CK_HLSLVectorToScalarCast: {
  3016. LValue LV = EmitLValue(E->getSubExpr());
  3017. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3018. llvm::ConstantInt *idxZero = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0);
  3019. llvm::Value *GEP = Builder.CreateInBoundsGEP(LV.getAddress(), {idxZero, idxZero});
  3020. return MakeAddrLValue(GEP, ToType);
  3021. } break;
  3022. case CK_HLSLCC_IntegralToFloating:
  3023. case CK_HLSLCC_FloatingToIntegral: {
  3024. LValue LV = EmitLValue(E->getSubExpr());
  3025. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3026. // bitcast to target type
  3027. llvm::Type *ResultType = ConvertType(ToType);
  3028. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  3029. return MakeAddrLValue(bitcast, ToType);
  3030. }
  3031. case CK_FlatConversion: {
  3032. // Just bitcast.
  3033. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3034. LValue LV = EmitLValue(E->getSubExpr());
  3035. llvm::Value *This = LV.getAddress();
  3036. // bitcast to target type
  3037. llvm::Type *ResultType = ConvertType(ToType);
  3038. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  3039. return MakeAddrLValue(bitcast, ToType);
  3040. }
  3041. case CK_HLSLDerivedToBase: {
  3042. // HLSL only single inheritance.
  3043. // Just GEP.
  3044. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3045. LValue LV = EmitLValue(E->getSubExpr());
  3046. llvm::Value *This = LV.getAddress();
  3047. // gep to target type
  3048. llvm::Type *ResultType = ConvertType(ToType);
  3049. unsigned level = 0;
  3050. llvm::Type *ToTy = ResultType->getPointerElementType();
  3051. llvm::Type *FromTy = This->getType()->getPointerElementType();
  3052. // For empty struct, just bitcast.
  3053. if (!isa<llvm::StructType>(FromTy->getStructElementType(0))) {
  3054. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  3055. return MakeAddrLValue(bitcast, ToType);
  3056. }
  3057. while (ToTy != FromTy) {
  3058. FromTy = FromTy->getStructElementType(0);
  3059. ++level;
  3060. }
  3061. llvm::Value *zeroIdx = Builder.getInt32(0);
  3062. SmallVector<llvm::Value *, 2> IdxList(level + 1, zeroIdx);
  3063. llvm::Value *GEP = Builder.CreateInBoundsGEP(This, IdxList);
  3064. return MakeAddrLValue(GEP, ToType);
  3065. }
  3066. case CK_HLSLMatrixSplat:
  3067. case CK_HLSLMatrixToScalarCast:
  3068. case CK_HLSLMatrixTruncationCast:
  3069. case CK_HLSLMatrixToVectorCast:
  3070. // Matrices should be handled above.
  3071. case CK_HLSLVectorToMatrixCast:
  3072. case CK_HLSLCC_IntegralCast:
  3073. case CK_HLSLCC_IntegralToBoolean:
  3074. case CK_HLSLCC_FloatingToBoolean:
  3075. case CK_HLSLCC_FloatingCast:
  3076. llvm_unreachable("Unhandled HLSL lvalue cast");
  3077. // HLSL Change Ends
  3078. case CK_ZeroToOCLEvent:
  3079. llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
  3080. }
  3081. llvm_unreachable("Unhandled lvalue cast kind?");
  3082. }
  3083. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  3084. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  3085. return getOpaqueLValueMapping(e);
  3086. }
  3087. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  3088. const FieldDecl *FD,
  3089. SourceLocation Loc) {
  3090. QualType FT = FD->getType();
  3091. LValue FieldLV = EmitLValueForField(LV, FD);
  3092. switch (getEvaluationKind(FT)) {
  3093. case TEK_Complex:
  3094. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  3095. case TEK_Aggregate:
  3096. return FieldLV.asAggregateRValue();
  3097. case TEK_Scalar:
  3098. return EmitLoadOfLValue(FieldLV, Loc);
  3099. }
  3100. llvm_unreachable("bad evaluation kind");
  3101. }
  3102. //===--------------------------------------------------------------------===//
  3103. // Expression Emission
  3104. //===--------------------------------------------------------------------===//
  3105. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3106. ReturnValueSlot ReturnValue) {
  3107. // Builtins never have block type.
  3108. if (E->getCallee()->getType()->isBlockPointerType())
  3109. return EmitBlockCallExpr(E, ReturnValue);
  3110. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3111. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3112. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3113. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3114. const Decl *TargetDecl = E->getCalleeDecl();
  3115. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  3116. if (unsigned builtinID = FD->getBuiltinID())
  3117. return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
  3118. // HLSL Change Starts
  3119. if (getLangOpts().HLSL) {
  3120. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(FD->getParent())) {
  3121. if (ns->getName() == "hlsl") {
  3122. // do hlsl intrinsic generation
  3123. return EmitHLSLBuiltinCallExpr(FD, E, ReturnValue);
  3124. }
  3125. }
  3126. }
  3127. // HLSL Change End
  3128. }
  3129. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3130. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
  3131. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3132. if (const auto *PseudoDtor =
  3133. dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
  3134. QualType DestroyedType = PseudoDtor->getDestroyedType();
  3135. if (getLangOpts().ObjCAutoRefCount &&
  3136. DestroyedType->isObjCLifetimeType() &&
  3137. (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  3138. DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
  3139. // Automatic Reference Counting:
  3140. // If the pseudo-expression names a retainable object with weak or
  3141. // strong lifetime, the object shall be released.
  3142. Expr *BaseExpr = PseudoDtor->getBase();
  3143. llvm::Value *BaseValue = nullptr;
  3144. Qualifiers BaseQuals;
  3145. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3146. if (PseudoDtor->isArrow()) {
  3147. BaseValue = EmitScalarExpr(BaseExpr);
  3148. const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
  3149. BaseQuals = PTy->getPointeeType().getQualifiers();
  3150. } else {
  3151. LValue BaseLV = EmitLValue(BaseExpr);
  3152. BaseValue = BaseLV.getAddress();
  3153. QualType BaseTy = BaseExpr->getType();
  3154. BaseQuals = BaseTy.getQualifiers();
  3155. }
  3156. switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
  3157. case Qualifiers::OCL_None:
  3158. case Qualifiers::OCL_ExplicitNone:
  3159. case Qualifiers::OCL_Autoreleasing:
  3160. break;
  3161. case Qualifiers::OCL_Strong:
  3162. EmitARCRelease(Builder.CreateLoad(BaseValue,
  3163. PseudoDtor->getDestroyedType().isVolatileQualified()),
  3164. ARCPreciseLifetime);
  3165. break;
  3166. case Qualifiers::OCL_Weak:
  3167. EmitARCDestroyWeak(BaseValue);
  3168. break;
  3169. }
  3170. } else {
  3171. // C++ [expr.pseudo]p1:
  3172. // The result shall only be used as the operand for the function call
  3173. // operator (), and the result of such a call has type void. The only
  3174. // effect is the evaluation of the postfix-expression before the dot or
  3175. // arrow.
  3176. EmitScalarExpr(E->getCallee());
  3177. }
  3178. return RValue::get(nullptr);
  3179. }
  3180. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  3181. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3182. TargetDecl);
  3183. }
  3184. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  3185. // Comma expressions just emit their LHS then their RHS as an l-value.
  3186. if (E->getOpcode() == BO_Comma) {
  3187. EmitIgnoredExpr(E->getLHS());
  3188. EnsureInsertPoint();
  3189. return EmitLValue(E->getRHS());
  3190. }
  3191. if (E->getOpcode() == BO_PtrMemD ||
  3192. E->getOpcode() == BO_PtrMemI)
  3193. return EmitPointerToDataMemberBinaryExpr(E);
  3194. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  3195. // Note that in all of these cases, __block variables need the RHS
  3196. // evaluated first just in case the variable gets moved by the RHS.
  3197. switch (getEvaluationKind(E->getType())) {
  3198. case TEK_Scalar: {
  3199. switch (E->getLHS()->getType().getObjCLifetime()) {
  3200. case Qualifiers::OCL_Strong:
  3201. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  3202. case Qualifiers::OCL_Autoreleasing:
  3203. return EmitARCStoreAutoreleasing(E).first;
  3204. // No reason to do any of these differently.
  3205. case Qualifiers::OCL_None:
  3206. case Qualifiers::OCL_ExplicitNone:
  3207. case Qualifiers::OCL_Weak:
  3208. break;
  3209. }
  3210. RValue RV = EmitAnyExpr(E->getRHS());
  3211. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  3212. EmitStoreThroughLValue(RV, LV);
  3213. return LV;
  3214. }
  3215. case TEK_Complex:
  3216. return EmitComplexAssignmentLValue(E);
  3217. case TEK_Aggregate:
  3218. return EmitAggExprToLValue(E);
  3219. }
  3220. llvm_unreachable("bad evaluation kind");
  3221. }
  3222. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  3223. RValue RV = EmitCallExpr(E);
  3224. if (!RV.isScalar())
  3225. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3226. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  3227. "Can't have a scalar return unless the return type is a "
  3228. "reference type!");
  3229. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3230. }
  3231. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  3232. // FIXME: This shouldn't require another copy.
  3233. return EmitAggExprToLValue(E);
  3234. }
  3235. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  3236. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  3237. && "binding l-value to type which needs a temporary");
  3238. AggValueSlot Slot = CreateAggTemp(E->getType());
  3239. EmitCXXConstructExpr(E, Slot);
  3240. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3241. }
  3242. LValue
  3243. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  3244. return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  3245. }
  3246. llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  3247. return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
  3248. ConvertType(E->getType())->getPointerTo());
  3249. }
  3250. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  3251. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
  3252. }
  3253. LValue
  3254. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  3255. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3256. Slot.setExternallyDestructed();
  3257. EmitAggExpr(E->getSubExpr(), Slot);
  3258. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
  3259. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3260. }
  3261. LValue
  3262. CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
  3263. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3264. EmitLambdaExpr(E, Slot);
  3265. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3266. }
  3267. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  3268. RValue RV = EmitObjCMessageExpr(E);
  3269. if (!RV.isScalar())
  3270. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3271. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  3272. "Can't have a scalar return unless the return type is a "
  3273. "reference type!");
  3274. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3275. }
  3276. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  3277. llvm::Value *V =
  3278. CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
  3279. return MakeAddrLValue(V, E->getType());
  3280. }
  3281. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  3282. const ObjCIvarDecl *Ivar) {
  3283. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  3284. }
  3285. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  3286. llvm::Value *BaseValue,
  3287. const ObjCIvarDecl *Ivar,
  3288. unsigned CVRQualifiers) {
  3289. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  3290. Ivar, CVRQualifiers);
  3291. }
  3292. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  3293. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  3294. llvm::Value *BaseValue = nullptr;
  3295. const Expr *BaseExpr = E->getBase();
  3296. Qualifiers BaseQuals;
  3297. QualType ObjectTy;
  3298. if (E->isArrow()) {
  3299. BaseValue = EmitScalarExpr(BaseExpr);
  3300. ObjectTy = BaseExpr->getType()->getPointeeType();
  3301. BaseQuals = ObjectTy.getQualifiers();
  3302. } else {
  3303. LValue BaseLV = EmitLValue(BaseExpr);
  3304. // FIXME: this isn't right for bitfields.
  3305. BaseValue = BaseLV.getAddress();
  3306. ObjectTy = BaseExpr->getType();
  3307. BaseQuals = ObjectTy.getQualifiers();
  3308. }
  3309. LValue LV =
  3310. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  3311. BaseQuals.getCVRQualifiers());
  3312. setObjCGCLValueClass(getContext(), E, LV);
  3313. return LV;
  3314. }
  3315. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  3316. // Can only get l-value for message expression returning aggregate type
  3317. RValue RV = EmitAnyExprToTemp(E);
  3318. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3319. }
  3320. RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
  3321. const CallExpr *E, ReturnValueSlot ReturnValue,
  3322. const Decl *TargetDecl, llvm::Value *Chain) {
  3323. // Get the actual function type. The callee type will always be a pointer to
  3324. // function type or a block pointer type.
  3325. assert(CalleeType->isFunctionPointerType() &&
  3326. "Call must have function pointer type!");
  3327. CalleeType = getContext().getCanonicalType(CalleeType);
  3328. const auto *FnType =
  3329. cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
  3330. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  3331. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  3332. if (llvm::Constant *PrefixSig =
  3333. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  3334. SanitizerScope SanScope(this);
  3335. llvm::Constant *FTRTTIConst =
  3336. CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
  3337. llvm::Type *PrefixStructTyElems[] = {
  3338. PrefixSig->getType(),
  3339. FTRTTIConst->getType()
  3340. };
  3341. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  3342. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  3343. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  3344. Callee, llvm::PointerType::getUnqual(PrefixStructTy));
  3345. llvm::Value *CalleeSigPtr =
  3346. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  3347. llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
  3348. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  3349. llvm::BasicBlock *Cont = createBasicBlock("cont");
  3350. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  3351. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  3352. EmitBlock(TypeCheck);
  3353. llvm::Value *CalleeRTTIPtr =
  3354. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  3355. llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
  3356. llvm::Value *CalleeRTTIMatch =
  3357. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  3358. llvm::Constant *StaticData[] = {
  3359. EmitCheckSourceLocation(E->getLocStart()),
  3360. EmitCheckTypeDescriptor(CalleeType)
  3361. };
  3362. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  3363. "function_type_mismatch", StaticData, Callee);
  3364. Builder.CreateBr(Cont);
  3365. EmitBlock(Cont);
  3366. }
  3367. }
  3368. // HLSL Change Begins
  3369. llvm::SmallVector<LValue, 8> castArgList;
  3370. // The argList of the CallExpr, may be update for out parameter
  3371. llvm::SmallVector<const Stmt *, 8> argList(E->arg_begin(), E->arg_end());
  3372. ConstExprIterator argBegin = argList.data();
  3373. ConstExprIterator argEnd = argList.data() + E->getNumArgs();
  3374. // out param conversion
  3375. CodeGenFunction::HLSLOutParamScope OutParamScope(*this);
  3376. auto MapTemp = [&](const VarDecl *LocalVD, llvm::Value *TmpArg) {
  3377. OutParamScope.addTemp(LocalVD, TmpArg);
  3378. };
  3379. if (getLangOpts().HLSL) {
  3380. if (const FunctionDecl *FD = E->getDirectCallee())
  3381. CGM.getHLSLRuntime().EmitHLSLOutParamConversionInit(*this, FD, E,
  3382. castArgList, argList, MapTemp);
  3383. }
  3384. // HLSL Change Ends
  3385. CallArgList Args;
  3386. if (Chain)
  3387. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  3388. CGM.getContext().VoidPtrTy);
  3389. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), argBegin, argEnd, // HLSL Change - use updated argList
  3390. E->getDirectCallee(), /*ParamsToSkip*/ 0);
  3391. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  3392. Args, FnType, /*isChainCall=*/Chain);
  3393. // C99 6.5.2.2p6:
  3394. // If the expression that denotes the called function has a type
  3395. // that does not include a prototype, [the default argument
  3396. // promotions are performed]. If the number of arguments does not
  3397. // equal the number of parameters, the behavior is undefined. If
  3398. // the function is defined with a type that includes a prototype,
  3399. // and either the prototype ends with an ellipsis (, ...) or the
  3400. // types of the arguments after promotion are not compatible with
  3401. // the types of the parameters, the behavior is undefined. If the
  3402. // function is defined with a type that does not include a
  3403. // prototype, and the types of the arguments after promotion are
  3404. // not compatible with those of the parameters after promotion,
  3405. // the behavior is undefined [except in some trivial cases].
  3406. // That is, in the general case, we should assume that a call
  3407. // through an unprototyped function type works like a *non-variadic*
  3408. // call. The way we make this work is to cast to the exact type
  3409. // of the promoted arguments.
  3410. //
  3411. // Chain calls use this same code path to add the invisible chain parameter
  3412. // to the function type.
  3413. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  3414. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  3415. CalleeTy = CalleeTy->getPointerTo();
  3416. Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
  3417. }
  3418. RValue CallVal = EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
  3419. // HLSL Change Begins
  3420. // out param conversion
  3421. // conversion and copy back after the call
  3422. if (getLangOpts().HLSL)
  3423. CGM.getHLSLRuntime().EmitHLSLOutParamConversionCopyBack(*this, castArgList);
  3424. // HLSL Change Ends
  3425. return CallVal;
  3426. }
  3427. LValue CodeGenFunction::
  3428. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  3429. llvm::Value *BaseV;
  3430. if (E->getOpcode() == BO_PtrMemI)
  3431. BaseV = EmitScalarExpr(E->getLHS());
  3432. else
  3433. BaseV = EmitLValue(E->getLHS()).getAddress();
  3434. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  3435. const MemberPointerType *MPT
  3436. = E->getRHS()->getType()->getAs<MemberPointerType>();
  3437. llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
  3438. *this, E, BaseV, OffsetV, MPT);
  3439. return MakeAddrLValue(AddV, MPT->getPointeeType());
  3440. }
  3441. /// Given the address of a temporary variable, produce an r-value of
  3442. /// its type.
  3443. RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
  3444. QualType type,
  3445. SourceLocation loc) {
  3446. LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
  3447. switch (getEvaluationKind(type)) {
  3448. case TEK_Complex:
  3449. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  3450. case TEK_Aggregate:
  3451. return lvalue.asAggregateRValue();
  3452. case TEK_Scalar:
  3453. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  3454. }
  3455. llvm_unreachable("bad evaluation kind");
  3456. }
  3457. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  3458. assert(Val->getType()->isFPOrFPVectorTy());
  3459. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  3460. return;
  3461. llvm::MDBuilder MDHelper(getLLVMContext());
  3462. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  3463. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  3464. }
  3465. namespace {
  3466. struct LValueOrRValue {
  3467. LValue LV;
  3468. RValue RV;
  3469. };
  3470. }
  3471. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  3472. const PseudoObjectExpr *E,
  3473. bool forLValue,
  3474. AggValueSlot slot) {
  3475. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  3476. // Find the result expression, if any.
  3477. const Expr *resultExpr = E->getResultExpr();
  3478. LValueOrRValue result;
  3479. for (PseudoObjectExpr::const_semantics_iterator
  3480. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  3481. const Expr *semantic = *i;
  3482. // If this semantic expression is an opaque value, bind it
  3483. // to the result of its source expression.
  3484. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  3485. // If this is the result expression, we may need to evaluate
  3486. // directly into the slot.
  3487. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  3488. OVMA opaqueData;
  3489. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  3490. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  3491. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  3492. LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
  3493. opaqueData = OVMA::bind(CGF, ov, LV);
  3494. result.RV = slot.asRValue();
  3495. // Otherwise, emit as normal.
  3496. } else {
  3497. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  3498. // If this is the result, also evaluate the result now.
  3499. if (ov == resultExpr) {
  3500. if (forLValue)
  3501. result.LV = CGF.EmitLValue(ov);
  3502. else
  3503. result.RV = CGF.EmitAnyExpr(ov, slot);
  3504. }
  3505. }
  3506. opaques.push_back(opaqueData);
  3507. // Otherwise, if the expression is the result, evaluate it
  3508. // and remember the result.
  3509. } else if (semantic == resultExpr) {
  3510. if (forLValue)
  3511. result.LV = CGF.EmitLValue(semantic);
  3512. else
  3513. result.RV = CGF.EmitAnyExpr(semantic, slot);
  3514. // Otherwise, evaluate the expression in an ignored context.
  3515. } else {
  3516. CGF.EmitIgnoredExpr(semantic);
  3517. }
  3518. }
  3519. // Unbind all the opaques now.
  3520. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  3521. opaques[i].unbind(CGF);
  3522. return result;
  3523. }
  3524. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  3525. AggValueSlot slot) {
  3526. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  3527. }
  3528. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  3529. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  3530. }