CGExpr.cpp 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019
  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. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  956. llvm::APInt &Min, llvm::APInt &End,
  957. bool StrictEnums) {
  958. const EnumType *ET = Ty->getAs<EnumType>();
  959. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  960. ET && !ET->getDecl()->isFixed();
  961. bool IsBool = hasBooleanRepresentation(Ty);
  962. if (!IsBool && !IsRegularCPlusPlusEnum)
  963. return false;
  964. if (IsBool) {
  965. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  966. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  967. } else {
  968. const EnumDecl *ED = ET->getDecl();
  969. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  970. unsigned Bitwidth = LTy->getScalarSizeInBits();
  971. unsigned NumNegativeBits = ED->getNumNegativeBits();
  972. unsigned NumPositiveBits = ED->getNumPositiveBits();
  973. if (NumNegativeBits) {
  974. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  975. assert(NumBits <= Bitwidth);
  976. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  977. Min = -End;
  978. } else {
  979. assert(NumPositiveBits <= Bitwidth);
  980. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  981. Min = llvm::APInt(Bitwidth, 0);
  982. }
  983. }
  984. return true;
  985. }
  986. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  987. llvm::APInt Min, End;
  988. if (!getRangeForType(*this, Ty, Min, End,
  989. CGM.getCodeGenOpts().StrictEnums))
  990. return nullptr;
  991. llvm::MDBuilder MDHelper(getLLVMContext());
  992. return MDHelper.createRange(Min, End);
  993. }
  994. llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  995. unsigned Alignment, QualType Ty,
  996. SourceLocation Loc,
  997. llvm::MDNode *TBAAInfo,
  998. QualType TBAABaseType,
  999. uint64_t TBAAOffset) {
  1000. // For better performance, handle vector loads differently.
  1001. if (Ty->isVectorType()) {
  1002. llvm::Value *V;
  1003. const llvm::Type *EltTy =
  1004. cast<llvm::PointerType>(Addr->getType())->getElementType();
  1005. const auto *VTy = cast<llvm::VectorType>(EltTy);
  1006. // Handle vectors of size 3, like size 4 for better performance.
  1007. if (VTy->getNumElements() == 3) {
  1008. // Bitcast to vec4 type.
  1009. llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
  1010. 4);
  1011. llvm::PointerType *ptVec4Ty =
  1012. llvm::PointerType::get(vec4Ty,
  1013. (cast<llvm::PointerType>(
  1014. Addr->getType()))->getAddressSpace());
  1015. llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
  1016. "castToVec4");
  1017. // Now load value.
  1018. llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1019. // Shuffle vector to get vec3.
  1020. llvm::Constant *Mask[] = {
  1021. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
  1022. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
  1023. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
  1024. };
  1025. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1026. V = Builder.CreateShuffleVector(LoadVal,
  1027. llvm::UndefValue::get(vec4Ty),
  1028. MaskV, "extractVec");
  1029. return EmitFromMemory(V, Ty);
  1030. }
  1031. }
  1032. // Atomic operations have to be done on integral types.
  1033. if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
  1034. LValue lvalue = LValue::MakeAddr(Addr, Ty,
  1035. CharUnits::fromQuantity(Alignment),
  1036. getContext(), TBAAInfo);
  1037. return EmitAtomicLoad(lvalue, Loc).getScalarVal();
  1038. }
  1039. // HLSL Change Begins
  1040. if (hlsl::IsHLSLMatType(Ty)) {
  1041. // Use matrix load to keep major info.
  1042. return CGM.getHLSLRuntime().EmitHLSLMatrixLoad(*this, Addr, Ty);
  1043. }
  1044. // HLSL Change Ends
  1045. llvm::LoadInst *Load = Builder.CreateLoad(Addr);
  1046. if (Volatile)
  1047. Load->setVolatile(true);
  1048. if (Alignment)
  1049. Load->setAlignment(Alignment);
  1050. if (TBAAInfo) {
  1051. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1052. TBAAOffset);
  1053. if (TBAAPath)
  1054. CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
  1055. }
  1056. bool NeedsBoolCheck =
  1057. SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
  1058. bool NeedsEnumCheck =
  1059. SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
  1060. if (NeedsBoolCheck || NeedsEnumCheck) {
  1061. SanitizerScope SanScope(this);
  1062. llvm::APInt Min, End;
  1063. if (getRangeForType(*this, Ty, Min, End, true)) {
  1064. --End;
  1065. llvm::Value *Check;
  1066. if (!Min)
  1067. Check = Builder.CreateICmpULE(
  1068. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1069. else {
  1070. llvm::Value *Upper = Builder.CreateICmpSLE(
  1071. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1072. llvm::Value *Lower = Builder.CreateICmpSGE(
  1073. Load, llvm::ConstantInt::get(getLLVMContext(), Min));
  1074. Check = Builder.CreateAnd(Upper, Lower);
  1075. }
  1076. llvm::Constant *StaticArgs[] = {
  1077. EmitCheckSourceLocation(Loc),
  1078. EmitCheckTypeDescriptor(Ty)
  1079. };
  1080. SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1081. EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
  1082. EmitCheckValue(Load));
  1083. }
  1084. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1085. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1086. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1087. return EmitFromMemory(Load, Ty);
  1088. }
  1089. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1090. // Bool has a different representation in memory than in registers.
  1091. if (hasBooleanRepresentation(Ty)) {
  1092. // This should really always be an i1, but sometimes it's already
  1093. // an i8, and it's awkward to track those cases down.
  1094. if (Value->getType()->isIntegerTy(1))
  1095. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1096. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1097. "wrong value rep of bool");
  1098. }
  1099. return Value;
  1100. }
  1101. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1102. // Bool has a different representation in memory than in registers.
  1103. if (hasBooleanRepresentation(Ty)) {
  1104. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1105. "wrong value rep of bool");
  1106. // HLSL Change Begin.
  1107. // Use ne v, 0 to convert to i1 instead of trunc.
  1108. return Builder.CreateICmpNE(
  1109. Value, llvm::ConstantInt::get(Value->getType(), 0), "tobool");
  1110. // HLSL Change End.
  1111. }
  1112. return Value;
  1113. }
  1114. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1115. bool Volatile, unsigned Alignment,
  1116. QualType Ty, llvm::MDNode *TBAAInfo,
  1117. bool isInit, QualType TBAABaseType,
  1118. uint64_t TBAAOffset) {
  1119. // Handle vectors differently to get better performance.
  1120. if (Ty->isVectorType()) {
  1121. llvm::Type *SrcTy = Value->getType();
  1122. auto *VecTy = cast<llvm::VectorType>(SrcTy);
  1123. // Handle vec3 special.
  1124. if (VecTy->getNumElements() == 3) {
  1125. llvm::LLVMContext &VMContext = getLLVMContext();
  1126. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1127. SmallVector<llvm::Constant*, 4> Mask;
  1128. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1129. 0));
  1130. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1131. 1));
  1132. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1133. 2));
  1134. Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
  1135. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1136. Value = Builder.CreateShuffleVector(Value,
  1137. llvm::UndefValue::get(VecTy),
  1138. MaskV, "extractVec");
  1139. SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
  1140. }
  1141. auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
  1142. if (DstPtr->getElementType() != SrcTy) {
  1143. llvm::Type *MemTy =
  1144. llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
  1145. Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
  1146. }
  1147. }
  1148. Value = EmitToMemory(Value, Ty);
  1149. if (Ty->isAtomicType() ||
  1150. (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
  1151. EmitAtomicStore(RValue::get(Value),
  1152. LValue::MakeAddr(Addr, Ty,
  1153. CharUnits::fromQuantity(Alignment),
  1154. getContext(), TBAAInfo),
  1155. isInit);
  1156. return;
  1157. }
  1158. // HLSL Change Begins
  1159. if (hlsl::IsHLSLMatType(Ty)) {
  1160. // Use matrix store to keep major info.
  1161. CGM.getHLSLRuntime().EmitHLSLMatrixStore(*this, Value, Addr, Ty);
  1162. return;
  1163. }
  1164. // HLSL Change Ends
  1165. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1166. if (Alignment)
  1167. Store->setAlignment(Alignment);
  1168. if (TBAAInfo) {
  1169. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1170. TBAAOffset);
  1171. if (TBAAPath)
  1172. CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
  1173. }
  1174. }
  1175. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1176. bool isInit) {
  1177. EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
  1178. lvalue.getAlignment().getQuantity(), lvalue.getType(),
  1179. lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
  1180. lvalue.getTBAAOffset());
  1181. }
  1182. // HLSL Change Begin - find immediate value for literal.
  1183. static llvm::Value *GetStoredValue(llvm::Value *Ptr) {
  1184. llvm::Value *V = nullptr;
  1185. for (llvm::User *U : Ptr->users()) {
  1186. if (llvm::StoreInst *ST = dyn_cast<llvm::StoreInst>(U)) {
  1187. if (V) {
  1188. // More than one store.
  1189. // Skip.
  1190. V = nullptr;
  1191. break;
  1192. }
  1193. V = ST->getValueOperand();
  1194. }
  1195. }
  1196. return V;
  1197. }
  1198. static bool IsLiteralType(QualType QT) {
  1199. if (const BuiltinType *BTy = QT->getAs<BuiltinType>()) {
  1200. if (BTy->getKind() == BuiltinType::LitFloat ||
  1201. BTy->getKind() == BuiltinType::LitInt)
  1202. return true;
  1203. }
  1204. return false;
  1205. }
  1206. // HLSL Change End.
  1207. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1208. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1209. /// returning the rvalue.
  1210. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1211. if (LV.isObjCWeak()) {
  1212. // load of a __weak object.
  1213. llvm::Value *AddrWeakObj = LV.getAddress();
  1214. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1215. AddrWeakObj));
  1216. }
  1217. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1218. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
  1219. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1220. return RValue::get(Object);
  1221. }
  1222. if (LV.isSimple()) {
  1223. assert(!LV.getType()->isFunctionType());
  1224. // HLSL Change Begin - find immediate value for literal.
  1225. if (IsLiteralType(LV.getType())) {
  1226. // The value must be stored only once.
  1227. // Scan all use to find it.
  1228. llvm::Value *Ptr = LV.getAddress();
  1229. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1230. return RValue::get(V);
  1231. }
  1232. }
  1233. // HLSL Change End.
  1234. // Everything needs a load.
  1235. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1236. }
  1237. if (LV.isVectorElt()) {
  1238. // HLSL Change Begin - find immediate value for literal.
  1239. if (IsLiteralType(LV.getType())) {
  1240. // The value must be stored only once.
  1241. // Scan all use to find it.
  1242. llvm::Value *Ptr = LV.getAddress();
  1243. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1244. return RValue::get(Builder.CreateExtractElement(V,
  1245. LV.getVectorIdx(), "vecext"));
  1246. }
  1247. }
  1248. // HLSL Change End.
  1249. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
  1250. LV.isVolatileQualified());
  1251. Load->setAlignment(LV.getAlignment().getQuantity());
  1252. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1253. "vecext"));
  1254. }
  1255. // If this is a reference to a subset of the elements of a vector, either
  1256. // shuffle the input or extract/insert them as appropriate.
  1257. if (LV.isExtVectorElt())
  1258. return EmitLoadOfExtVectorElementLValue(LV);
  1259. // Global Register variables always invoke intrinsics
  1260. if (LV.isGlobalReg())
  1261. return EmitLoadOfGlobalRegLValue(LV);
  1262. // HLSL Change Starts
  1263. if (LV.isExtMatrixElt())
  1264. return EmitLoadOfExtMatrixElementLValue(LV);
  1265. // HLSL Change Ends
  1266. assert(LV.isBitField() && "Unknown LValue type!");
  1267. return EmitLoadOfBitfieldLValue(LV);
  1268. }
  1269. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
  1270. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1271. CharUnits Align = LV.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1272. // Get the output type.
  1273. llvm::Type *ResLTy = ConvertType(LV.getType());
  1274. llvm::Value *Ptr = LV.getBitFieldAddr();
  1275. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1276. LV.isVolatileQualified(),
  1277. "bf.load");
  1278. if (Info.IsSigned) {
  1279. assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
  1280. unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
  1281. if (HighBits)
  1282. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1283. if (Info.Offset + HighBits)
  1284. Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
  1285. } else {
  1286. if (Info.Offset)
  1287. Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
  1288. if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
  1289. Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
  1290. Info.Size),
  1291. "bf.clear");
  1292. }
  1293. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1294. return RValue::get(Val);
  1295. }
  1296. // If this is a reference to a subset of the elements of a vector, create an
  1297. // appropriate shufflevector.
  1298. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1299. llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
  1300. LV.isVolatileQualified());
  1301. Load->setAlignment(LV.getAlignment().getQuantity());
  1302. llvm::Value *Vec = Load;
  1303. const llvm::Constant *Elts = LV.getExtVectorElts();
  1304. // If the result of the expression is a non-vector type, we must be extracting
  1305. // a single element. Just codegen as an extractelement.
  1306. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1307. // HLSL Change Starts
  1308. if (ExprVT == nullptr && getContext().getLangOpts().HLSL)
  1309. ExprVT =
  1310. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), LV.getType());
  1311. // HLSL Change Ends
  1312. // HLSL Change Begin - find immediate value for literal.
  1313. QualType QT = LV.getType();
  1314. if (ExprVT) {
  1315. QT = ExprVT->getElementType();
  1316. }
  1317. if (IsLiteralType(QT)) {
  1318. // The value must be stored only once.
  1319. // Scan all use to find it.
  1320. llvm::Value *Ptr = LV.getExtVectorAddr();
  1321. if (llvm::Value *V = GetStoredValue(Ptr)) {
  1322. Vec = V;
  1323. }
  1324. }
  1325. // HLSL Change End.
  1326. if (!ExprVT) {
  1327. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1328. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1329. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1330. }
  1331. // Always use shuffle vector to try to retain the original program structure
  1332. unsigned NumResultElts = ExprVT->getNumElements();
  1333. SmallVector<llvm::Constant*, 4> Mask;
  1334. for (unsigned i = 0; i != NumResultElts; ++i)
  1335. Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
  1336. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1337. Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
  1338. MaskV);
  1339. return RValue::get(Vec);
  1340. }
  1341. /// @brief Generates lvalue for partial ext_vector access.
  1342. llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1343. llvm::Value *VectorAddress = LV.getExtVectorAddr();
  1344. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1345. QualType EQT = ExprVT->getElementType();
  1346. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1347. llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
  1348. llvm::Value *CastToPointerElement =
  1349. Builder.CreateBitCast(VectorAddress,
  1350. VectorElementPtrToTy, "conv.ptr.element");
  1351. const llvm::Constant *Elts = LV.getExtVectorElts();
  1352. unsigned ix = getAccessedFieldNo(0, Elts);
  1353. llvm::Value *VectorBasePtrPlusIx =
  1354. Builder.CreateInBoundsGEP(CastToPointerElement,
  1355. llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
  1356. return VectorBasePtrPlusIx;
  1357. }
  1358. /// @brief Load of global gamed gegisters are always calls to intrinsics.
  1359. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1360. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1361. "Bad type for register variable");
  1362. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1363. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1364. // We accept integer and pointer types only
  1365. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1366. llvm::Type *Ty = OrigTy;
  1367. if (OrigTy->isPointerTy())
  1368. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1369. llvm::Type *Types[] = { Ty };
  1370. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1371. llvm::Value *Call = Builder.CreateCall(
  1372. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1373. if (OrigTy->isPointerTy())
  1374. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1375. return RValue::get(Call);
  1376. }
  1377. // HLSL Change Starts
  1378. RValue CodeGenFunction::EmitLoadOfExtMatrixElementLValue(LValue LV) {
  1379. // TODO: Matrix swizzle members - emit
  1380. return RValue();
  1381. }
  1382. // HLSL Change Ends
  1383. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1384. /// lvalue, where both are guaranteed to the have the same type, and that type
  1385. /// is 'Ty'.
  1386. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1387. bool isInit) {
  1388. if (!Dst.isSimple()) {
  1389. if (Dst.isVectorElt()) {
  1390. // Read/modify/write the vector, inserting the new element.
  1391. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
  1392. Dst.isVolatileQualified());
  1393. Load->setAlignment(Dst.getAlignment().getQuantity());
  1394. llvm::Value *Vec = Load;
  1395. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1396. Dst.getVectorIdx(), "vecins");
  1397. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
  1398. Dst.isVolatileQualified());
  1399. Store->setAlignment(Dst.getAlignment().getQuantity());
  1400. return;
  1401. }
  1402. // If this is an update of extended vector elements, insert them as
  1403. // appropriate.
  1404. if (Dst.isExtVectorElt())
  1405. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1406. if (Dst.isGlobalReg())
  1407. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1408. assert(Dst.isBitField() && "Unknown LValue type");
  1409. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1410. }
  1411. // There's special magic for assigning into an ARC-qualified l-value.
  1412. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1413. switch (Lifetime) {
  1414. case Qualifiers::OCL_None:
  1415. llvm_unreachable("present but none");
  1416. case Qualifiers::OCL_ExplicitNone:
  1417. // nothing special
  1418. break;
  1419. case Qualifiers::OCL_Strong:
  1420. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1421. return;
  1422. case Qualifiers::OCL_Weak:
  1423. EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
  1424. return;
  1425. case Qualifiers::OCL_Autoreleasing:
  1426. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1427. Src.getScalarVal()));
  1428. // fall into the normal path
  1429. break;
  1430. }
  1431. }
  1432. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1433. // load of a __weak object.
  1434. llvm::Value *LvalueDst = Dst.getAddress();
  1435. llvm::Value *src = Src.getScalarVal();
  1436. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1437. return;
  1438. }
  1439. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1440. // load of a __strong object.
  1441. llvm::Value *LvalueDst = Dst.getAddress();
  1442. llvm::Value *src = Src.getScalarVal();
  1443. if (Dst.isObjCIvar()) {
  1444. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1445. llvm::Type *ResultType = ConvertType(getContext().LongTy);
  1446. llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
  1447. llvm::Value *dst = RHS;
  1448. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1449. llvm::Value *LHS =
  1450. Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
  1451. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1452. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1453. BytesBetween);
  1454. } else if (Dst.isGlobalObjCRef()) {
  1455. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1456. Dst.isThreadLocalRef());
  1457. }
  1458. else
  1459. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1460. return;
  1461. }
  1462. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1463. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1464. }
  1465. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1466. llvm::Value **Result) {
  1467. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1468. CharUnits Align = Dst.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1469. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1470. llvm::Value *Ptr = Dst.getBitFieldAddr();
  1471. // Get the source value, truncated to the width of the bit-field.
  1472. llvm::Value *SrcVal = Src.getScalarVal();
  1473. // Cast the source to the storage type and shift it into place.
  1474. SrcVal = Builder.CreateIntCast(SrcVal,
  1475. Ptr->getType()->getPointerElementType(),
  1476. /*IsSigned=*/false);
  1477. llvm::Value *MaskedVal = SrcVal;
  1478. // See if there are other bits in the bitfield's storage we'll need to load
  1479. // and mask together with source before storing.
  1480. if (Info.StorageSize != Info.Size) {
  1481. assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
  1482. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1483. Dst.isVolatileQualified(),
  1484. "bf.load");
  1485. // Mask the source value as needed.
  1486. if (!hasBooleanRepresentation(Dst.getType()))
  1487. SrcVal = Builder.CreateAnd(SrcVal,
  1488. llvm::APInt::getLowBitsSet(Info.StorageSize,
  1489. Info.Size),
  1490. "bf.value");
  1491. MaskedVal = SrcVal;
  1492. if (Info.Offset)
  1493. SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
  1494. // Mask out the original value.
  1495. Val = Builder.CreateAnd(Val,
  1496. ~llvm::APInt::getBitsSet(Info.StorageSize,
  1497. Info.Offset,
  1498. Info.Offset + Info.Size),
  1499. "bf.clear");
  1500. // Or together the unchanged values and the source value.
  1501. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1502. } else {
  1503. assert(Info.Offset == 0);
  1504. }
  1505. // Write the new value back out.
  1506. Builder.CreateAlignedStore(SrcVal, Ptr, Align.getQuantity(),
  1507. Dst.isVolatileQualified());
  1508. // Return the new value of the bit-field, if requested.
  1509. if (Result) {
  1510. llvm::Value *ResultVal = MaskedVal;
  1511. // Sign extend the value if needed.
  1512. if (Info.IsSigned) {
  1513. assert(Info.Size <= Info.StorageSize);
  1514. unsigned HighBits = Info.StorageSize - Info.Size;
  1515. if (HighBits) {
  1516. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1517. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1518. }
  1519. }
  1520. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1521. "bf.result.cast");
  1522. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1523. }
  1524. }
  1525. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1526. LValue Dst) {
  1527. // This access turns into a read/modify/write of the vector. Load the input
  1528. // value now.
  1529. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
  1530. Dst.isVolatileQualified());
  1531. Load->setAlignment(Dst.getAlignment().getQuantity());
  1532. llvm::Value *Vec = Load;
  1533. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1534. llvm::Value *SrcVal = Src.getScalarVal();
  1535. // HLSL Change Starts
  1536. const VectorType *VTy = Dst.getType()->getAs<VectorType>();
  1537. if (VTy == nullptr && getContext().getLangOpts().HLSL)
  1538. VTy =
  1539. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), Dst.getType());
  1540. llvm::Value * VecDstPtr = Dst.getExtVectorAddr();
  1541. llvm::Value *Zero = Builder.getInt32(0);
  1542. if (VTy) {
  1543. llvm::Type *VecTy = VecDstPtr->getType()->getPointerElementType();
  1544. unsigned NumSrcElts = VTy->getNumElements();
  1545. if (VecTy->getVectorNumElements() == NumSrcElts) {
  1546. // Full vector write, create one store.
  1547. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1548. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1549. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1550. Vec = Builder.CreateInsertElement(Vec, SrcElt, Elt);
  1551. }
  1552. }
  1553. Builder.CreateStore(Vec, VecDstPtr);
  1554. } else {
  1555. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1556. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1557. llvm::Value *EltGEP = Builder.CreateGEP(VecDstPtr, {Zero, Elt});
  1558. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1559. Builder.CreateStore(SrcElt, EltGEP);
  1560. }
  1561. }
  1562. }
  1563. } else {
  1564. // If the Src is a scalar (not a vector) it must be updating one element.
  1565. llvm::Value *EltGEP = Builder.CreateGEP(
  1566. VecDstPtr, {Zero, Elts->getAggregateElement((unsigned)0)});
  1567. Builder.CreateStore(SrcVal, EltGEP);
  1568. }
  1569. return;
  1570. // HLSL Change Ends
  1571. if (VTy) { // HLSL Change
  1572. unsigned NumSrcElts = VTy->getNumElements();
  1573. unsigned NumDstElts =
  1574. cast<llvm::VectorType>(Vec->getType())->getNumElements();
  1575. if (NumDstElts == NumSrcElts) {
  1576. // Use shuffle vector is the src and destination are the same number of
  1577. // elements and restore the vector mask since it is on the side it will be
  1578. // stored.
  1579. SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
  1580. for (unsigned i = 0; i != NumSrcElts; ++i)
  1581. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
  1582. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1583. Vec = Builder.CreateShuffleVector(SrcVal,
  1584. llvm::UndefValue::get(Vec->getType()),
  1585. MaskV);
  1586. } else if (NumDstElts > NumSrcElts) {
  1587. // Extended the source vector to the same length and then shuffle it
  1588. // into the destination.
  1589. // FIXME: since we're shuffling with undef, can we just use the indices
  1590. // into that? This could be simpler.
  1591. SmallVector<llvm::Constant*, 4> ExtMask;
  1592. for (unsigned i = 0; i != NumSrcElts; ++i)
  1593. ExtMask.push_back(Builder.getInt32(i));
  1594. ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
  1595. llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
  1596. llvm::Value *ExtSrcVal =
  1597. Builder.CreateShuffleVector(SrcVal,
  1598. llvm::UndefValue::get(SrcVal->getType()),
  1599. ExtMaskV);
  1600. // build identity
  1601. SmallVector<llvm::Constant*, 4> Mask;
  1602. for (unsigned i = 0; i != NumDstElts; ++i)
  1603. Mask.push_back(Builder.getInt32(i));
  1604. // When the vector size is odd and .odd or .hi is used, the last element
  1605. // of the Elts constant array will be one past the size of the vector.
  1606. // Ignore the last element here, if it is greater than the mask size.
  1607. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  1608. NumSrcElts--;
  1609. // modify when what gets shuffled in
  1610. for (unsigned i = 0; i != NumSrcElts; ++i)
  1611. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
  1612. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1613. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
  1614. } else {
  1615. // We should never shorten the vector
  1616. llvm_unreachable("unexpected shorten vector length");
  1617. }
  1618. } else {
  1619. // If the Src is a scalar (not a vector) it must be updating one element.
  1620. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1621. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1622. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  1623. }
  1624. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
  1625. Dst.isVolatileQualified());
  1626. Store->setAlignment(Dst.getAlignment().getQuantity());
  1627. }
  1628. /// @brief Store of global named registers are always calls to intrinsics.
  1629. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  1630. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  1631. "Bad type for register variable");
  1632. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1633. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  1634. assert(RegName && "Register LValue is not metadata");
  1635. // We accept integer and pointer types only
  1636. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  1637. llvm::Type *Ty = OrigTy;
  1638. if (OrigTy->isPointerTy())
  1639. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1640. llvm::Type *Types[] = { Ty };
  1641. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  1642. llvm::Value *Value = Src.getScalarVal();
  1643. if (OrigTy->isPointerTy())
  1644. Value = Builder.CreatePtrToInt(Value, Ty);
  1645. Builder.CreateCall(
  1646. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  1647. }
  1648. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  1649. // generating write-barries API. It is currently a global, ivar,
  1650. // or neither.
  1651. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  1652. LValue &LV,
  1653. bool IsMemberAccess=false) {
  1654. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  1655. return;
  1656. if (isa<ObjCIvarRefExpr>(E)) {
  1657. QualType ExpTy = E->getType();
  1658. if (IsMemberAccess && ExpTy->isPointerType()) {
  1659. // If ivar is a structure pointer, assigning to field of
  1660. // this struct follows gcc's behavior and makes it a non-ivar
  1661. // writer-barrier conservatively.
  1662. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1663. if (ExpTy->isRecordType()) {
  1664. LV.setObjCIvar(false);
  1665. return;
  1666. }
  1667. }
  1668. LV.setObjCIvar(true);
  1669. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  1670. LV.setBaseIvarExp(Exp->getBase());
  1671. LV.setObjCArray(E->getType()->isArrayType());
  1672. return;
  1673. }
  1674. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  1675. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  1676. if (VD->hasGlobalStorage()) {
  1677. LV.setGlobalObjCRef(true);
  1678. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  1679. }
  1680. }
  1681. LV.setObjCArray(E->getType()->isArrayType());
  1682. return;
  1683. }
  1684. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  1685. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1686. return;
  1687. }
  1688. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  1689. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1690. if (LV.isObjCIvar()) {
  1691. // If cast is to a structure pointer, follow gcc's behavior and make it
  1692. // a non-ivar write-barrier.
  1693. QualType ExpTy = E->getType();
  1694. if (ExpTy->isPointerType())
  1695. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1696. if (ExpTy->isRecordType())
  1697. LV.setObjCIvar(false);
  1698. }
  1699. return;
  1700. }
  1701. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  1702. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  1703. return;
  1704. }
  1705. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  1706. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1707. return;
  1708. }
  1709. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  1710. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1711. return;
  1712. }
  1713. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  1714. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1715. return;
  1716. }
  1717. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  1718. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  1719. if (LV.isObjCIvar() && !LV.isObjCArray())
  1720. // Using array syntax to assigning to what an ivar points to is not
  1721. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  1722. LV.setObjCIvar(false);
  1723. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  1724. // Using array syntax to assigning to what global points to is not
  1725. // same as assigning to the global itself. {id *G;} G[i] = 0;
  1726. LV.setGlobalObjCRef(false);
  1727. return;
  1728. }
  1729. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  1730. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  1731. // We don't know if member is an 'ivar', but this flag is looked at
  1732. // only in the context of LV.isObjCIvar().
  1733. LV.setObjCArray(E->getType()->isArrayType());
  1734. return;
  1735. }
  1736. }
  1737. static llvm::Value *
  1738. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  1739. llvm::Value *V, llvm::Type *IRType,
  1740. StringRef Name = StringRef()) {
  1741. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  1742. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  1743. }
  1744. static LValue EmitThreadPrivateVarDeclLValue(
  1745. CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
  1746. llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
  1747. V = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, V, Loc);
  1748. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1749. return CGF.MakeAddrLValue(V, T, Alignment);
  1750. }
  1751. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  1752. const Expr *E, const VarDecl *VD) {
  1753. QualType T = E->getType();
  1754. // If it's thread_local, emit a call to its wrapper function instead.
  1755. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  1756. CGF.CGM.getCXXABI().usesThreadWrapperFunction())
  1757. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  1758. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  1759. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  1760. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1761. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  1762. LValue LV;
  1763. // Emit reference to the private copy of the variable if it is an OpenMP
  1764. // threadprivate variable.
  1765. if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1766. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, V, RealVarTy, Alignment,
  1767. E->getExprLoc());
  1768. if (VD->getType()->isReferenceType()) {
  1769. llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
  1770. LI->setAlignment(Alignment.getQuantity());
  1771. V = LI;
  1772. LV = CGF.MakeNaturalAlignAddrLValue(V, T);
  1773. } else {
  1774. LV = CGF.MakeAddrLValue(V, T, Alignment);
  1775. }
  1776. setObjCGCLValueClass(CGF.getContext(), E, LV);
  1777. return LV;
  1778. }
  1779. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
  1780. const Expr *E, const FunctionDecl *FD) {
  1781. llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
  1782. if (!FD->hasPrototype()) {
  1783. if (const FunctionProtoType *Proto =
  1784. FD->getType()->getAs<FunctionProtoType>()) {
  1785. // Ugly case: for a K&R-style definition, the type of the definition
  1786. // isn't the same as the type of a use. Correct for this with a
  1787. // bitcast.
  1788. QualType NoProtoType =
  1789. CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
  1790. NoProtoType = CGF.getContext().getPointerType(NoProtoType);
  1791. V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
  1792. }
  1793. }
  1794. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  1795. return CGF.MakeAddrLValue(V, E->getType(), Alignment);
  1796. }
  1797. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  1798. llvm::Value *ThisValue) {
  1799. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  1800. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  1801. return CGF.EmitLValueForField(LV, FD);
  1802. }
  1803. /// Named Registers are named metadata pointing to the register name
  1804. /// which will be read from/written to as an argument to the intrinsic
  1805. /// @llvm.read/write_register.
  1806. /// So far, only the name is being passed down, but other options such as
  1807. /// register type, allocation type or even optimization options could be
  1808. /// passed down via the metadata node.
  1809. static LValue EmitGlobalNamedRegister(const VarDecl *VD,
  1810. CodeGenModule &CGM,
  1811. CharUnits Alignment) {
  1812. SmallString<64> Name("llvm.named.register.");
  1813. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  1814. assert(Asm->getLabel().size() < 64-Name.size() &&
  1815. "Register name too big");
  1816. Name.append(Asm->getLabel());
  1817. llvm::NamedMDNode *M =
  1818. CGM.getModule().getOrInsertNamedMetadata(Name);
  1819. if (M->getNumOperands() == 0) {
  1820. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  1821. Asm->getLabel());
  1822. llvm::Metadata *Ops[] = {Str};
  1823. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  1824. }
  1825. return LValue::MakeGlobalReg(
  1826. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)),
  1827. VD->getType(), Alignment);
  1828. }
  1829. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  1830. const NamedDecl *ND = E->getDecl();
  1831. CharUnits Alignment = getContext().getDeclAlign(ND);
  1832. QualType T = E->getType();
  1833. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1834. // Global Named registers access via intrinsics only
  1835. if (VD->getStorageClass() == SC_Register &&
  1836. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  1837. return EmitGlobalNamedRegister(VD, CGM, Alignment);
  1838. // A DeclRefExpr for a reference initialized by a constant expression can
  1839. // appear without being odr-used. Directly emit the constant initializer.
  1840. const Expr *Init = VD->getAnyInitializer(VD);
  1841. if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
  1842. VD->isUsableInConstantExpressions(getContext()) &&
  1843. VD->checkInitIsICE()) {
  1844. llvm::Constant *Val =
  1845. CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
  1846. assert(Val && "failed to emit reference constant expression");
  1847. // FIXME: Eventually we will want to emit vector element references.
  1848. return MakeAddrLValue(Val, T, Alignment);
  1849. }
  1850. // Check for captured variables.
  1851. if (E->refersToEnclosingVariableOrCapture()) {
  1852. if (auto *FD = LambdaCaptureFields.lookup(VD))
  1853. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  1854. else if (CapturedStmtInfo) {
  1855. if (auto *V = LocalDeclMap.lookup(VD))
  1856. return MakeAddrLValue(V, T, Alignment);
  1857. else
  1858. return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  1859. CapturedStmtInfo->getContextValue());
  1860. }
  1861. assert(isa<BlockDecl>(CurCodeDecl));
  1862. return MakeAddrLValue(GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()),
  1863. T, Alignment);
  1864. }
  1865. }
  1866. // FIXME: We should be able to assert this for FunctionDecls as well!
  1867. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  1868. // those with a valid source location.
  1869. assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
  1870. !E->getLocation().isValid()) &&
  1871. "Should not use decl without marking it used!");
  1872. if (ND->hasAttr<WeakRefAttr>()) {
  1873. const auto *VD = cast<ValueDecl>(ND);
  1874. llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
  1875. return MakeAddrLValue(Aliasee, T, Alignment);
  1876. }
  1877. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1878. // Check if this is a global variable.
  1879. if (VD->hasLinkage() || VD->isStaticDataMember())
  1880. return EmitGlobalVarDeclLValue(*this, E, VD);
  1881. bool isBlockVariable = VD->hasAttr<BlocksAttr>();
  1882. llvm::Value *V = LocalDeclMap.lookup(VD);
  1883. if (!V && VD->isStaticLocal())
  1884. V = CGM.getOrCreateStaticVarDecl(
  1885. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
  1886. // Check if variable is threadprivate.
  1887. if (V && getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1888. return EmitThreadPrivateVarDeclLValue(
  1889. *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
  1890. Alignment, E->getExprLoc());
  1891. assert(V && "DeclRefExpr not entered in LocalDeclMap?");
  1892. if (isBlockVariable)
  1893. V = BuildBlockByrefAddress(V, VD);
  1894. LValue LV;
  1895. // HLSL Change Begins
  1896. if (getLangOpts().HLSL) {
  1897. // In hlsl, the referent type is for out parameter.
  1898. // No pointer of pointer temp alloca created for it.
  1899. // So always use V directly.
  1900. LV = MakeAddrLValue(V, T, Alignment);
  1901. } else
  1902. // HLSL Change Ends
  1903. if (VD->getType()->isReferenceType()) {
  1904. llvm::LoadInst *LI = Builder.CreateLoad(V);
  1905. LI->setAlignment(Alignment.getQuantity());
  1906. V = LI;
  1907. LV = MakeNaturalAlignAddrLValue(V, T);
  1908. } else {
  1909. LV = MakeAddrLValue(V, T, Alignment);
  1910. }
  1911. bool isLocalStorage = VD->hasLocalStorage();
  1912. bool NonGCable = isLocalStorage &&
  1913. !VD->getType()->isReferenceType() &&
  1914. !isBlockVariable;
  1915. if (NonGCable) {
  1916. LV.getQuals().removeObjCGCAttr();
  1917. LV.setNonGC(true);
  1918. }
  1919. bool isImpreciseLifetime =
  1920. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  1921. if (isImpreciseLifetime)
  1922. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  1923. setObjCGCLValueClass(getContext(), E, LV);
  1924. return LV;
  1925. }
  1926. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  1927. return EmitFunctionDeclLValue(*this, E, FD);
  1928. llvm_unreachable("Unhandled DeclRefExpr");
  1929. }
  1930. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  1931. // __extension__ doesn't affect lvalue-ness.
  1932. if (E->getOpcode() == UO_Extension)
  1933. return EmitLValue(E->getSubExpr());
  1934. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  1935. switch (E->getOpcode()) {
  1936. default: llvm_unreachable("Unknown unary operator lvalue!");
  1937. case UO_Deref: {
  1938. QualType T = E->getSubExpr()->getType()->getPointeeType();
  1939. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  1940. LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
  1941. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  1942. // We should not generate __weak write barrier on indirect reference
  1943. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  1944. // But, we continue to generate __strong write barrier on indirect write
  1945. // into a pointer to object.
  1946. if (getLangOpts().ObjC1 &&
  1947. getLangOpts().getGC() != LangOptions::NonGC &&
  1948. LV.isObjCWeak())
  1949. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  1950. return LV;
  1951. }
  1952. case UO_Real:
  1953. case UO_Imag: {
  1954. LValue LV = EmitLValue(E->getSubExpr());
  1955. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  1956. llvm::Value *Addr = LV.getAddress();
  1957. // __real is valid on scalars. This is a faster way of testing that.
  1958. // __imag can only produce an rvalue on scalars.
  1959. if (E->getOpcode() == UO_Real &&
  1960. !cast<llvm::PointerType>(Addr->getType())
  1961. ->getElementType()->isStructTy()) {
  1962. assert(E->getSubExpr()->getType()->isArithmeticType());
  1963. return LV;
  1964. }
  1965. assert(E->getSubExpr()->getType()->isAnyComplexType());
  1966. unsigned Idx = E->getOpcode() == UO_Imag;
  1967. return MakeAddrLValue(
  1968. Builder.CreateStructGEP(nullptr, LV.getAddress(), Idx, "idx"), ExprTy);
  1969. }
  1970. case UO_PreInc:
  1971. case UO_PreDec: {
  1972. LValue LV = EmitLValue(E->getSubExpr());
  1973. bool isInc = E->getOpcode() == UO_PreInc;
  1974. if (E->getType()->isAnyComplexType())
  1975. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1976. else
  1977. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1978. return LV;
  1979. }
  1980. }
  1981. }
  1982. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  1983. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  1984. E->getType());
  1985. }
  1986. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  1987. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  1988. E->getType());
  1989. }
  1990. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  1991. auto SL = E->getFunctionName();
  1992. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  1993. StringRef FnName = CurFn->getName();
  1994. if (FnName.startswith("\01"))
  1995. FnName = FnName.substr(1);
  1996. StringRef NameItems[] = {
  1997. PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
  1998. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  1999. if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
  2000. auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str(), 1);
  2001. return MakeAddrLValue(C, E->getType());
  2002. }
  2003. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  2004. return MakeAddrLValue(C, E->getType());
  2005. }
  2006. /// Emit a type description suitable for use by a runtime sanitizer library. The
  2007. /// format of a type descriptor is
  2008. ///
  2009. /// \code
  2010. /// { i16 TypeKind, i16 TypeInfo }
  2011. /// \endcode
  2012. ///
  2013. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  2014. /// integer, 1 for a floating point value, and -1 for anything else.
  2015. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  2016. // Only emit each type's descriptor once.
  2017. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  2018. return C;
  2019. uint16_t TypeKind = -1;
  2020. uint16_t TypeInfo = 0;
  2021. if (T->isIntegerType()) {
  2022. TypeKind = 0;
  2023. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  2024. (T->isSignedIntegerType() ? 1 : 0);
  2025. } else if (T->isFloatingType()) {
  2026. TypeKind = 1;
  2027. TypeInfo = getContext().getTypeSize(T);
  2028. }
  2029. // Format the type name as if for a diagnostic, including quotes and
  2030. // optionally an 'aka'.
  2031. SmallString<32> Buffer;
  2032. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  2033. (intptr_t)T.getAsOpaquePtr(),
  2034. StringRef(), StringRef(), None, Buffer,
  2035. None);
  2036. llvm::Constant *Components[] = {
  2037. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  2038. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  2039. };
  2040. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  2041. auto *GV = new llvm::GlobalVariable(
  2042. CGM.getModule(), Descriptor->getType(),
  2043. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  2044. GV->setUnnamedAddr(true);
  2045. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  2046. // Remember the descriptor for this type.
  2047. CGM.setTypeDescriptorInMap(T, GV);
  2048. return GV;
  2049. }
  2050. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  2051. llvm::Type *TargetTy = IntPtrTy;
  2052. // Floating-point types which fit into intptr_t are bitcast to integers
  2053. // and then passed directly (after zero-extension, if necessary).
  2054. if (V->getType()->isFloatingPointTy()) {
  2055. unsigned Bits = V->getType()->getPrimitiveSizeInBits();
  2056. if (Bits <= TargetTy->getIntegerBitWidth())
  2057. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  2058. Bits));
  2059. }
  2060. // Integers which fit in intptr_t are zero-extended and passed directly.
  2061. if (V->getType()->isIntegerTy() &&
  2062. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2063. return Builder.CreateZExt(V, TargetTy);
  2064. // Pointers are passed directly, everything else is passed by address.
  2065. if (!V->getType()->isPointerTy()) {
  2066. llvm::Value *Ptr = CreateTempAlloca(V->getType());
  2067. Builder.CreateStore(V, Ptr);
  2068. V = Ptr;
  2069. }
  2070. return Builder.CreatePtrToInt(V, TargetTy);
  2071. }
  2072. /// \brief Emit a representation of a SourceLocation for passing to a handler
  2073. /// in a sanitizer runtime library. The format for this data is:
  2074. /// \code
  2075. /// struct SourceLocation {
  2076. /// const char *Filename;
  2077. /// int32_t Line, Column;
  2078. /// };
  2079. /// \endcode
  2080. /// For an invalid SourceLocation, the Filename pointer is null.
  2081. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2082. llvm::Constant *Filename;
  2083. int Line, Column;
  2084. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2085. if (PLoc.isValid()) {
  2086. auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
  2087. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
  2088. Filename = FilenameGV;
  2089. Line = PLoc.getLine();
  2090. Column = PLoc.getColumn();
  2091. } else {
  2092. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2093. Line = Column = 0;
  2094. }
  2095. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2096. Builder.getInt32(Column)};
  2097. return llvm::ConstantStruct::getAnon(Data);
  2098. }
  2099. namespace {
  2100. /// \brief Specify under what conditions this check can be recovered
  2101. enum class CheckRecoverableKind {
  2102. /// Always terminate program execution if this check fails.
  2103. Unrecoverable,
  2104. /// Check supports recovering, runtime has both fatal (noreturn) and
  2105. /// non-fatal handlers for this check.
  2106. Recoverable,
  2107. /// Runtime conditionally aborts, always need to support recovery.
  2108. AlwaysRecoverable
  2109. };
  2110. }
  2111. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2112. assert(llvm::countPopulation(Kind) == 1);
  2113. switch (Kind) {
  2114. case SanitizerKind::Vptr:
  2115. return CheckRecoverableKind::AlwaysRecoverable;
  2116. case SanitizerKind::Return:
  2117. case SanitizerKind::Unreachable:
  2118. return CheckRecoverableKind::Unrecoverable;
  2119. default:
  2120. return CheckRecoverableKind::Recoverable;
  2121. }
  2122. }
  2123. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2124. llvm::FunctionType *FnType,
  2125. ArrayRef<llvm::Value *> FnArgs,
  2126. StringRef CheckName,
  2127. CheckRecoverableKind RecoverKind, bool IsFatal,
  2128. llvm::BasicBlock *ContBB) {
  2129. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2130. bool NeedsAbortSuffix =
  2131. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2132. std::string FnName = ("__ubsan_handle_" + CheckName +
  2133. (NeedsAbortSuffix ? "_abort" : "")).str();
  2134. bool MayReturn =
  2135. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2136. llvm::AttrBuilder B;
  2137. if (!MayReturn) {
  2138. B.addAttribute(llvm::Attribute::NoReturn)
  2139. .addAttribute(llvm::Attribute::NoUnwind);
  2140. }
  2141. B.addAttribute(llvm::Attribute::UWTable);
  2142. llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
  2143. FnType, FnName,
  2144. llvm::AttributeSet::get(CGF.getLLVMContext(),
  2145. llvm::AttributeSet::FunctionIndex, B));
  2146. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2147. if (!MayReturn) {
  2148. HandlerCall->setDoesNotReturn();
  2149. CGF.Builder.CreateUnreachable();
  2150. } else {
  2151. CGF.Builder.CreateBr(ContBB);
  2152. }
  2153. }
  2154. void CodeGenFunction::EmitCheck(
  2155. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2156. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2157. ArrayRef<llvm::Value *> DynamicArgs) {
  2158. assert(IsSanitizerScope);
  2159. assert(Checked.size() > 0);
  2160. llvm::Value *FatalCond = nullptr;
  2161. llvm::Value *RecoverableCond = nullptr;
  2162. llvm::Value *TrapCond = nullptr;
  2163. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2164. llvm::Value *Check = Checked[i].first;
  2165. // -fsanitize-trap= overrides -fsanitize-recover=.
  2166. llvm::Value *&Cond =
  2167. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2168. ? TrapCond
  2169. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2170. ? RecoverableCond
  2171. : FatalCond;
  2172. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2173. }
  2174. if (TrapCond)
  2175. EmitTrapCheck(TrapCond);
  2176. if (!FatalCond && !RecoverableCond)
  2177. return;
  2178. llvm::Value *JointCond;
  2179. if (FatalCond && RecoverableCond)
  2180. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2181. else
  2182. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2183. assert(JointCond);
  2184. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2185. assert(SanOpts.has(Checked[0].second));
  2186. #ifndef NDEBUG
  2187. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2188. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2189. "All recoverable kinds in a single check must be same!");
  2190. assert(SanOpts.has(Checked[i].second));
  2191. }
  2192. #endif
  2193. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2194. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2195. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2196. // Give hint that we very much don't expect to execute the handler
  2197. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2198. llvm::MDBuilder MDHelper(getLLVMContext());
  2199. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2200. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2201. EmitBlock(Handlers);
  2202. // Emit handler arguments and create handler function type.
  2203. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2204. auto *InfoPtr =
  2205. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2206. llvm::GlobalVariable::PrivateLinkage, Info);
  2207. InfoPtr->setUnnamedAddr(true);
  2208. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2209. SmallVector<llvm::Value *, 4> Args;
  2210. SmallVector<llvm::Type *, 4> ArgTypes;
  2211. Args.reserve(DynamicArgs.size() + 1);
  2212. ArgTypes.reserve(DynamicArgs.size() + 1);
  2213. // Handler functions take an i8* pointing to the (handler-specific) static
  2214. // information block, followed by a sequence of intptr_t arguments
  2215. // representing operand values.
  2216. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2217. ArgTypes.push_back(Int8PtrTy);
  2218. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2219. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2220. ArgTypes.push_back(IntPtrTy);
  2221. }
  2222. llvm::FunctionType *FnType =
  2223. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2224. if (!FatalCond || !RecoverableCond) {
  2225. // Simple case: we need to generate a single handler call, either
  2226. // fatal, or non-fatal.
  2227. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
  2228. (FatalCond != nullptr), Cont);
  2229. } else {
  2230. // Emit two handler calls: first one for set of unrecoverable checks,
  2231. // another one for recoverable.
  2232. llvm::BasicBlock *NonFatalHandlerBB =
  2233. createBasicBlock("non_fatal." + CheckName);
  2234. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2235. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2236. EmitBlock(FatalHandlerBB);
  2237. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
  2238. NonFatalHandlerBB);
  2239. EmitBlock(NonFatalHandlerBB);
  2240. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
  2241. Cont);
  2242. }
  2243. EmitBlock(Cont);
  2244. }
  2245. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
  2246. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2247. // If we're optimizing, collapse all calls to trap down to just one per
  2248. // function to save on code size.
  2249. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  2250. TrapBB = createBasicBlock("trap");
  2251. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2252. EmitBlock(TrapBB);
  2253. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2254. TrapCall->setDoesNotReturn();
  2255. TrapCall->setDoesNotThrow();
  2256. Builder.CreateUnreachable();
  2257. } else {
  2258. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2259. }
  2260. EmitBlock(Cont);
  2261. }
  2262. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  2263. llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
  2264. if (!CGM.getCodeGenOpts().TrapFuncName.empty())
  2265. TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
  2266. "trap-func-name",
  2267. CGM.getCodeGenOpts().TrapFuncName);
  2268. return TrapCall;
  2269. }
  2270. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  2271. /// array to pointer, return the array subexpression.
  2272. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  2273. // If this isn't just an array->pointer decay, bail out.
  2274. const auto *CE = dyn_cast<CastExpr>(E);
  2275. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  2276. return nullptr;
  2277. // If this is a decay from variable width array, bail out.
  2278. const Expr *SubExpr = CE->getSubExpr();
  2279. if (SubExpr->getType()->isVariableArrayType())
  2280. return nullptr;
  2281. return SubExpr;
  2282. }
  2283. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2284. bool Accessed) {
  2285. // The index must always be an integer, which is not an aggregate. Emit it.
  2286. llvm::Value *Idx = EmitScalarExpr(E->getIdx());
  2287. QualType IdxTy = E->getIdx()->getType();
  2288. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  2289. if (SanOpts.has(SanitizerKind::ArrayBounds))
  2290. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  2291. // If the base is a vector type, then we are forming a vector element lvalue
  2292. // with this subscript.
  2293. if (E->getBase()->getType()->isVectorType() &&
  2294. !isa<ExtVectorElementExpr>(E->getBase())) {
  2295. // Emit the vector as an lvalue to get its address.
  2296. LValue LHS = EmitLValue(E->getBase());
  2297. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  2298. return LValue::MakeVectorElt(LHS.getAddress(), Idx,
  2299. E->getBase()->getType(), LHS.getAlignment());
  2300. }
  2301. // Extend or truncate the index type to 32 or 64-bits.
  2302. if (Idx->getType() != IntPtrTy)
  2303. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  2304. // HLSL Change Starts
  2305. const Expr *Array = isSimpleArrayDecayOperand(E->getBase());
  2306. assert((!getLangOpts().HLSL || nullptr == Array) &&
  2307. "else array decay snuck in AST for HLSL");
  2308. // HLSL Change Ends
  2309. // We know that the pointer points to a type of the correct size, unless the
  2310. // size is a VLA or Objective-C interface.
  2311. llvm::Value *Address = nullptr;
  2312. CharUnits ArrayAlignment;
  2313. if (isa<ExtVectorElementExpr>(E->getBase())) {
  2314. LValue LV = EmitLValue(E->getBase());
  2315. Address = EmitExtVectorElementLValue(LV);
  2316. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2317. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  2318. QualType EQT = ExprVT->getElementType();
  2319. return MakeAddrLValue(Address, EQT,
  2320. getContext().getTypeAlignInChars(EQT));
  2321. }
  2322. else if (const VariableArrayType *vla =
  2323. getContext().getAsVariableArrayType(E->getType())) {
  2324. // The base must be a pointer, which is not an aggregate. Emit
  2325. // it. It needs to be emitted first in case it's what captures
  2326. // the VLA bounds.
  2327. Address = EmitScalarExpr(E->getBase());
  2328. // The element count here is the total number of non-VLA elements.
  2329. llvm::Value *numElements = getVLASize(vla).first;
  2330. // Effectively, the multiply by the VLA size is part of the GEP.
  2331. // GEP indexes are signed, and scaling an index isn't permitted to
  2332. // signed-overflow, so we use the same semantics for our explicit
  2333. // multiply. We suppress this if overflow is not undefined behavior.
  2334. if (getLangOpts().isSignedOverflowDefined()) {
  2335. Idx = Builder.CreateMul(Idx, numElements);
  2336. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2337. } else {
  2338. Idx = Builder.CreateNSWMul(Idx, numElements);
  2339. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2340. }
  2341. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  2342. // Indexing over an interface, as in "NSString *P; P[4];"
  2343. llvm::Value *InterfaceSize =
  2344. llvm::ConstantInt::get(Idx->getType(),
  2345. getContext().getTypeSizeInChars(OIT).getQuantity());
  2346. Idx = Builder.CreateMul(Idx, InterfaceSize);
  2347. // The base must be a pointer, which is not an aggregate. Emit it.
  2348. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2349. Address = EmitCastToVoidPtr(Base);
  2350. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2351. Address = Builder.CreateBitCast(Address, Base->getType());
  2352. } else if (!getLangOpts().HLSL && Array) { // HLSL Change - No Array to pointer decay for HLSL
  2353. // If this is A[i] where A is an array, the frontend will have decayed the
  2354. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  2355. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  2356. // "gep x, i" here. Emit one "gep A, 0, i".
  2357. assert(Array->getType()->isArrayType() &&
  2358. "Array to pointer decay must have array source type!");
  2359. LValue ArrayLV;
  2360. // For simple multidimensional array indexing, set the 'accessed' flag for
  2361. // better bounds-checking of the base expression.
  2362. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  2363. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2364. else
  2365. ArrayLV = EmitLValue(Array);
  2366. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2367. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2368. llvm::Value *Args[] = { Zero, Idx };
  2369. // Propagate the alignment from the array itself to the result.
  2370. ArrayAlignment = ArrayLV.getAlignment();
  2371. if (getLangOpts().isSignedOverflowDefined())
  2372. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2373. else
  2374. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2375. } else {
  2376. // HLSL Change Starts
  2377. const ArrayType *AT = dyn_cast<ArrayType>(E->getBase()->getType()->getCanonicalTypeUnqualified());
  2378. if (getContext().getLangOpts().HLSL && AT) {
  2379. LValue ArrayLV;
  2380. // For simple multidimensional array indexing, set the 'accessed' flag for
  2381. // better bounds-checking of the base expression.
  2382. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E->getBase()))
  2383. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2384. else
  2385. ArrayLV = EmitLValue(E->getBase());
  2386. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2387. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2388. llvm::Value *Args[] = { Zero, Idx };
  2389. // Propagate the alignment from the array itself to the result.
  2390. ArrayAlignment = ArrayLV.getAlignment();
  2391. if (getLangOpts().isSignedOverflowDefined())
  2392. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2393. else
  2394. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2395. } else {
  2396. // HLSL Change Ends
  2397. // The base must be a pointer, which is not an aggregate. Emit it.
  2398. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2399. if (getLangOpts().isSignedOverflowDefined())
  2400. Address = Builder.CreateGEP(Base, Idx, "arrayidx");
  2401. else
  2402. Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
  2403. } // HLSL Change
  2404. }
  2405. QualType T = E->getBase()->getType()->getPointeeType();
  2406. // HLSL Change Starts
  2407. if (getContext().getLangOpts().HLSL && T.isNull()) {
  2408. T = QualType(E->getBase()->getType()->getArrayElementTypeNoTypeQual(), 0);
  2409. }
  2410. // HLSL Change Ends
  2411. assert(!T.isNull() &&
  2412. "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
  2413. // Limit the alignment to that of the result type.
  2414. LValue LV;
  2415. if (!ArrayAlignment.isZero()) {
  2416. CharUnits Align = getContext().getTypeAlignInChars(T);
  2417. ArrayAlignment = std::min(Align, ArrayAlignment);
  2418. LV = MakeAddrLValue(Address, T, ArrayAlignment);
  2419. } else {
  2420. LV = MakeNaturalAlignAddrLValue(Address, T);
  2421. }
  2422. LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
  2423. if (getLangOpts().ObjC1 &&
  2424. getLangOpts().getGC() != LangOptions::NonGC) {
  2425. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2426. setObjCGCLValueClass(getContext(), E, LV);
  2427. }
  2428. return LV;
  2429. }
  2430. static
  2431. llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
  2432. SmallVectorImpl<unsigned> &Elts) {
  2433. SmallVector<llvm::Constant*, 4> CElts;
  2434. for (unsigned i = 0, e = Elts.size(); i != e; ++i)
  2435. CElts.push_back(Builder.getInt32(Elts[i]));
  2436. return llvm::ConstantVector::get(CElts);
  2437. }
  2438. LValue CodeGenFunction::
  2439. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  2440. // Emit the base vector as an l-value.
  2441. LValue Base;
  2442. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2443. if (E->isArrow()) {
  2444. // If it is a pointer to a vector, emit the address and form an lvalue with
  2445. // it.
  2446. llvm::Value *Ptr = EmitScalarExpr(E->getBase());
  2447. const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
  2448. Base = MakeAddrLValue(Ptr, PT->getPointeeType());
  2449. Base.getQuals().removeObjCGCAttr();
  2450. } else if (E->getBase()->isGLValue()) {
  2451. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2452. // emit the base as an lvalue.
  2453. assert(E->getBase()->getType()->isVectorType());
  2454. Base = EmitLValue(E->getBase());
  2455. } else {
  2456. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2457. assert(E->getBase()->getType()->isVectorType() &&
  2458. "Result must be a vector");
  2459. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2460. // Store the vector to memory (because LValue wants an address).
  2461. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2462. Builder.CreateStore(Vec, VecMem);
  2463. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2464. }
  2465. QualType type =
  2466. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2467. // Encode the element access list into a vector of unsigned indices.
  2468. SmallVector<unsigned, 4> Indices;
  2469. E->getEncodedElementAccess(Indices);
  2470. if (Base.isSimple()) {
  2471. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2472. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2473. Base.getAlignment());
  2474. }
  2475. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2476. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2477. SmallVector<llvm::Constant *, 4> CElts;
  2478. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2479. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2480. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2481. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2482. Base.getAlignment());
  2483. }
  2484. // HLSL Change Starts
  2485. LValue
  2486. CodeGenFunction::EmitExtMatrixElementExpr(const ExtMatrixElementExpr *E) {
  2487. LValue Base;
  2488. assert(!E->isArrow() && "ExtMatrixElementExpr's base will not be Arrow");
  2489. if (E->getBase()->isGLValue()) {
  2490. // if the base is an lvalue ( as in the case of foo.x.x),
  2491. // emit the base as an lvalue.
  2492. const Expr *base = E->getBase();
  2493. assert(hlsl::IsHLSLMatType(base->getType()));
  2494. Base = EmitLValue(base);
  2495. } else {
  2496. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2497. assert(hlsl::IsHLSLMatType(E->getBase()->getType()) &&
  2498. "Result must be a vector");
  2499. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2500. // Store the vector to memory (because LValue wants an address).
  2501. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2502. Builder.CreateStore(Vec, VecMem);
  2503. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2504. }
  2505. // Encode the element access list into a vector of unsigned indices.
  2506. SmallVector<unsigned, 4> Indices;
  2507. E->getEncodedElementAccess(Indices);
  2508. llvm::Type *ResultTy =
  2509. ConvertType(getContext().getLValueReferenceType(E->getType()));
  2510. llvm::Value *matBase = nullptr;
  2511. llvm::Constant *CV = nullptr;
  2512. if (Base.isSimple()) {
  2513. SmallVector<llvm::Constant *, 4> CElts;
  2514. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2515. CElts.push_back(Builder.getInt32(Indices[i]));
  2516. CV = llvm::ConstantVector::get(CElts);
  2517. matBase = Base.getAddress();
  2518. } else {
  2519. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2520. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2521. SmallVector<llvm::Constant *, 4> CElts;
  2522. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2523. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2524. CV = llvm::ConstantVector::get(CElts);
  2525. matBase = Base.getExtVectorAddr();
  2526. }
  2527. llvm::Value *Result = CGM.getHLSLRuntime().EmitHLSLMatrixElement(
  2528. *this, ResultTy, {matBase, CV}, E->getBase()->getType());
  2529. return MakeAddrLValue(Result, E->getType());
  2530. }
  2531. LValue
  2532. CodeGenFunction::EmitHLSLVectorElementExpr(const HLSLVectorElementExpr *E) {
  2533. // Emit the base vector as an l-value.
  2534. // Clone EmitExtVectorElementExpr for now
  2535. // TODO: difference between ExtVector and HlslVector
  2536. LValue Base;
  2537. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2538. if (E->isArrow()) {
  2539. // If it is a pointer to a vector, emit the address and form an lvalue with
  2540. // it.
  2541. assert(!getLangOpts().HLSL && "this will not happen for hlsl");
  2542. } else if (E->getBase()->isGLValue()) {
  2543. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2544. // emit the base as an lvalue.
  2545. const Expr *base = E->getBase();
  2546. assert(hlsl::IsHLSLVecType(base->getType()));
  2547. Base = EmitLValue(base);
  2548. } else {
  2549. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2550. assert(hlsl::IsHLSLVecType(E->getBase()->getType()) &&
  2551. "Result must be a vector");
  2552. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2553. // Store the vector to memory (because LValue wants an address).
  2554. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2555. Builder.CreateStore(Vec, VecMem);
  2556. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2557. }
  2558. QualType type =
  2559. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2560. // Encode the element access list into a vector of unsigned indices.
  2561. SmallVector<unsigned, 4> Indices;
  2562. E->getEncodedElementAccess(Indices);
  2563. if (Base.isSimple()) {
  2564. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2565. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2566. Base.getAlignment());
  2567. }
  2568. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2569. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2570. SmallVector<llvm::Constant *, 4> CElts;
  2571. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2572. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2573. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2574. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2575. Base.getAlignment());
  2576. }
  2577. // HLSL Change Ends
  2578. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  2579. Expr *BaseExpr = E->getBase();
  2580. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  2581. LValue BaseLV;
  2582. if (E->isArrow()) {
  2583. llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
  2584. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  2585. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
  2586. BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
  2587. } else
  2588. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  2589. NamedDecl *ND = E->getMemberDecl();
  2590. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  2591. LValue LV = EmitLValueForField(BaseLV, Field);
  2592. setObjCGCLValueClass(getContext(), E, LV);
  2593. return LV;
  2594. }
  2595. if (auto *VD = dyn_cast<VarDecl>(ND))
  2596. return EmitGlobalVarDeclLValue(*this, E, VD);
  2597. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2598. return EmitFunctionDeclLValue(*this, E, FD);
  2599. llvm_unreachable("Unhandled member declaration!");
  2600. }
  2601. /// Given that we are currently emitting a lambda, emit an l-value for
  2602. /// one of its members.
  2603. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  2604. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  2605. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  2606. QualType LambdaTagType =
  2607. getContext().getTagDeclType(Field->getParent());
  2608. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  2609. return EmitLValueForField(LambdaLV, Field);
  2610. }
  2611. LValue CodeGenFunction::EmitLValueForField(LValue base,
  2612. const FieldDecl *field) {
  2613. if (field->isBitField()) {
  2614. const CGRecordLayout &RL =
  2615. CGM.getTypes().getCGRecordLayout(field->getParent());
  2616. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  2617. llvm::Value *Addr = base.getAddress();
  2618. unsigned Idx = RL.getLLVMFieldNo(field);
  2619. if (Idx != 0)
  2620. // For structs, we GEP to the field that the record layout suggests.
  2621. Addr = Builder.CreateStructGEP(nullptr, Addr, Idx, field->getName());
  2622. // Get the access type.
  2623. llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
  2624. getLLVMContext(), Info.StorageSize,
  2625. CGM.getContext().getTargetAddressSpace(base.getType()));
  2626. if (Addr->getType() != PtrTy)
  2627. Addr = Builder.CreateBitCast(Addr, PtrTy);
  2628. QualType fieldType =
  2629. field->getType().withCVRQualifiers(base.getVRQualifiers());
  2630. return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
  2631. }
  2632. const RecordDecl *rec = field->getParent();
  2633. QualType type = field->getType();
  2634. CharUnits alignment = getContext().getDeclAlign(field);
  2635. // FIXME: It should be impossible to have an LValue without alignment for a
  2636. // complete type.
  2637. if (!base.getAlignment().isZero())
  2638. alignment = std::min(alignment, base.getAlignment());
  2639. bool mayAlias = rec->hasAttr<MayAliasAttr>();
  2640. llvm::Value *addr = base.getAddress();
  2641. unsigned cvr = base.getVRQualifiers();
  2642. bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
  2643. if (rec->isUnion()) {
  2644. // For unions, there is no pointer adjustment.
  2645. assert(!type->isReferenceType() && "union has reference member");
  2646. // TODO: handle path-aware TBAA for union.
  2647. TBAAPath = false;
  2648. } else {
  2649. // For structs, we GEP to the field that the record layout suggests.
  2650. unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  2651. addr = Builder.CreateStructGEP(nullptr, addr, idx, field->getName());
  2652. // If this is a reference field, load the reference right now.
  2653. if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
  2654. llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
  2655. if (cvr & Qualifiers::Volatile) load->setVolatile(true);
  2656. load->setAlignment(alignment.getQuantity());
  2657. // Loading the reference will disable path-aware TBAA.
  2658. TBAAPath = false;
  2659. if (CGM.shouldUseTBAA()) {
  2660. llvm::MDNode *tbaa;
  2661. if (mayAlias)
  2662. tbaa = CGM.getTBAAInfo(getContext().CharTy);
  2663. else
  2664. tbaa = CGM.getTBAAInfo(type);
  2665. if (tbaa)
  2666. CGM.DecorateInstruction(load, tbaa);
  2667. }
  2668. addr = load;
  2669. mayAlias = false;
  2670. type = refType->getPointeeType();
  2671. if (type->isIncompleteType())
  2672. alignment = CharUnits();
  2673. else
  2674. alignment = getContext().getTypeAlignInChars(type);
  2675. cvr = 0; // qualifiers don't recursively apply to referencee
  2676. }
  2677. }
  2678. // Make sure that the address is pointing to the right type. This is critical
  2679. // for both unions and structs. A union needs a bitcast, a struct element
  2680. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2681. // type.
  2682. addr = EmitBitCastOfLValueToProperType(*this, addr,
  2683. CGM.getTypes().ConvertTypeForMem(type),
  2684. field->getName());
  2685. if (field->hasAttr<AnnotateAttr>())
  2686. addr = EmitFieldAnnotations(field, addr);
  2687. LValue LV = MakeAddrLValue(addr, type, alignment);
  2688. LV.getQuals().addCVRQualifiers(cvr);
  2689. if (TBAAPath) {
  2690. const ASTRecordLayout &Layout =
  2691. getContext().getASTRecordLayout(field->getParent());
  2692. // Set the base type to be the base type of the base LValue and
  2693. // update offset to be relative to the base type.
  2694. LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
  2695. LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
  2696. Layout.getFieldOffset(field->getFieldIndex()) /
  2697. getContext().getCharWidth());
  2698. }
  2699. // __weak attribute on a field is ignored.
  2700. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  2701. LV.getQuals().removeObjCGCAttr();
  2702. // Fields of may_alias structs act like 'char' for TBAA purposes.
  2703. // FIXME: this should get propagated down through anonymous structs
  2704. // and unions.
  2705. if (mayAlias && LV.getTBAAInfo())
  2706. LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
  2707. return LV;
  2708. }
  2709. LValue
  2710. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  2711. const FieldDecl *Field) {
  2712. QualType FieldType = Field->getType();
  2713. if (!FieldType->isReferenceType())
  2714. return EmitLValueForField(Base, Field);
  2715. const CGRecordLayout &RL =
  2716. CGM.getTypes().getCGRecordLayout(Field->getParent());
  2717. unsigned idx = RL.getLLVMFieldNo(Field);
  2718. llvm::Value *V = Builder.CreateStructGEP(nullptr, Base.getAddress(), idx);
  2719. assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
  2720. // Make sure that the address is pointing to the right type. This is critical
  2721. // for both unions and structs. A union needs a bitcast, a struct element
  2722. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2723. // type.
  2724. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  2725. V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
  2726. CharUnits Alignment = getContext().getDeclAlign(Field);
  2727. // FIXME: It should be impossible to have an LValue without alignment for a
  2728. // complete type.
  2729. if (!Base.getAlignment().isZero())
  2730. Alignment = std::min(Alignment, Base.getAlignment());
  2731. return MakeAddrLValue(V, FieldType, Alignment);
  2732. }
  2733. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  2734. if (E->isFileScope()) {
  2735. llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  2736. return MakeAddrLValue(GlobalPtr, E->getType());
  2737. }
  2738. if (E->getType()->isVariablyModifiedType())
  2739. // make sure to emit the VLA size.
  2740. EmitVariablyModifiedType(E->getType());
  2741. llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  2742. const Expr *InitExpr = E->getInitializer();
  2743. LValue Result = MakeAddrLValue(DeclPtr, E->getType());
  2744. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  2745. /*Init*/ true);
  2746. return Result;
  2747. }
  2748. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  2749. if (!E->isGLValue())
  2750. // Initializing an aggregate temporary in C++11: T{...}.
  2751. return EmitAggExprToLValue(E);
  2752. // An lvalue initializer list must be initializing a reference.
  2753. assert(E->getNumInits() == 1 && "reference init with multiple values");
  2754. return EmitLValue(E->getInit(0));
  2755. }
  2756. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  2757. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  2758. /// LValue is returned and the current block has been terminated.
  2759. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  2760. const Expr *Operand) {
  2761. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  2762. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  2763. return None;
  2764. }
  2765. return CGF.EmitLValue(Operand);
  2766. }
  2767. LValue CodeGenFunction::
  2768. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  2769. if (!expr->isGLValue()) {
  2770. // ?: here should be an aggregate.
  2771. assert(hasAggregateEvaluationKind(expr->getType()) &&
  2772. "Unexpected conditional operator!");
  2773. return EmitAggExprToLValue(expr);
  2774. }
  2775. OpaqueValueMapping binding(*this, expr);
  2776. const Expr *condExpr = expr->getCond();
  2777. bool CondExprBool;
  2778. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  2779. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  2780. if (!CondExprBool) std::swap(live, dead);
  2781. if (!ContainsLabel(dead)) {
  2782. // If the true case is live, we need to track its region.
  2783. if (CondExprBool)
  2784. incrementProfileCounter(expr);
  2785. return EmitLValue(live);
  2786. }
  2787. }
  2788. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  2789. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  2790. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  2791. ConditionalEvaluation eval(*this);
  2792. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  2793. // Any temporaries created here are conditional.
  2794. EmitBlock(lhsBlock);
  2795. incrementProfileCounter(expr);
  2796. eval.begin(*this);
  2797. Optional<LValue> lhs =
  2798. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  2799. eval.end(*this);
  2800. if (lhs && !lhs->isSimple())
  2801. return EmitUnsupportedLValue(expr, "conditional operator");
  2802. lhsBlock = Builder.GetInsertBlock();
  2803. if (lhs)
  2804. Builder.CreateBr(contBlock);
  2805. // Any temporaries created here are conditional.
  2806. EmitBlock(rhsBlock);
  2807. eval.begin(*this);
  2808. Optional<LValue> rhs =
  2809. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  2810. eval.end(*this);
  2811. if (rhs && !rhs->isSimple())
  2812. return EmitUnsupportedLValue(expr, "conditional operator");
  2813. rhsBlock = Builder.GetInsertBlock();
  2814. EmitBlock(contBlock);
  2815. if (lhs && rhs) {
  2816. llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
  2817. 2, "cond-lvalue");
  2818. phi->addIncoming(lhs->getAddress(), lhsBlock);
  2819. phi->addIncoming(rhs->getAddress(), rhsBlock);
  2820. return MakeAddrLValue(phi, expr->getType());
  2821. } else {
  2822. assert((lhs || rhs) &&
  2823. "both operands of glvalue conditional are throw-expressions?");
  2824. return lhs ? *lhs : *rhs;
  2825. }
  2826. }
  2827. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  2828. /// type. If the cast is to a reference, we can have the usual lvalue result,
  2829. /// otherwise if a cast is needed by the code generator in an lvalue context,
  2830. /// then it must mean that we need the address of an aggregate in order to
  2831. /// access one of its members. This can happen for all the reasons that casts
  2832. /// are permitted with aggregate result, including noop aggregate casts, and
  2833. /// cast from scalar to union.
  2834. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  2835. // HLSL Change Begins
  2836. if (hlsl::IsHLSLMatType(E->getType()) || hlsl::IsHLSLMatType(E->getSubExpr()->getType())) {
  2837. LValue LV = EmitLValue(E->getSubExpr());
  2838. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2839. llvm::Type *RetTy = ConvertType(ToType);
  2840. // type not changed, LValueToRValue, CStyleCast may go this path
  2841. if (LV.getAddress()->getType() == RetTy)
  2842. return LV;
  2843. llvm::Value *cast = CGM.getHLSLRuntime().EmitHLSLMatrixOperationCall(*this, E, RetTy, { LV.getAddress() });
  2844. return MakeAddrLValue(cast, ToType);
  2845. }
  2846. // HLSL Change Ends
  2847. switch (E->getCastKind()) {
  2848. case CK_ToVoid:
  2849. case CK_BitCast:
  2850. case CK_ArrayToPointerDecay:
  2851. case CK_FunctionToPointerDecay:
  2852. case CK_NullToMemberPointer:
  2853. case CK_NullToPointer:
  2854. case CK_IntegralToPointer:
  2855. case CK_PointerToIntegral:
  2856. case CK_PointerToBoolean:
  2857. case CK_VectorSplat:
  2858. case CK_IntegralCast:
  2859. case CK_IntegralToBoolean:
  2860. case CK_IntegralToFloating:
  2861. case CK_FloatingToIntegral:
  2862. case CK_FloatingToBoolean:
  2863. case CK_FloatingCast:
  2864. case CK_FloatingRealToComplex:
  2865. case CK_FloatingComplexToReal:
  2866. case CK_FloatingComplexToBoolean:
  2867. case CK_FloatingComplexCast:
  2868. case CK_FloatingComplexToIntegralComplex:
  2869. case CK_IntegralRealToComplex:
  2870. case CK_IntegralComplexToReal:
  2871. case CK_IntegralComplexToBoolean:
  2872. case CK_IntegralComplexCast:
  2873. case CK_IntegralComplexToFloatingComplex:
  2874. case CK_DerivedToBaseMemberPointer:
  2875. case CK_BaseToDerivedMemberPointer:
  2876. case CK_MemberPointerToBoolean:
  2877. case CK_ReinterpretMemberPointer:
  2878. case CK_AnyPointerToBlockPointerCast:
  2879. case CK_ARCProduceObject:
  2880. case CK_ARCConsumeObject:
  2881. case CK_ARCReclaimReturnedObject:
  2882. case CK_ARCExtendBlockObject:
  2883. case CK_CopyAndAutoreleaseBlockObject:
  2884. case CK_AddressSpaceConversion:
  2885. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  2886. case CK_Dependent:
  2887. llvm_unreachable("dependent cast kind in IR gen!");
  2888. case CK_BuiltinFnToFnPtr:
  2889. llvm_unreachable("builtin functions are handled elsewhere");
  2890. // These are never l-values; just use the aggregate emission code.
  2891. case CK_NonAtomicToAtomic:
  2892. case CK_AtomicToNonAtomic:
  2893. return EmitAggExprToLValue(E);
  2894. case CK_Dynamic: {
  2895. LValue LV = EmitLValue(E->getSubExpr());
  2896. llvm::Value *V = LV.getAddress();
  2897. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  2898. return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  2899. }
  2900. case CK_ConstructorConversion:
  2901. case CK_UserDefinedConversion:
  2902. case CK_CPointerToObjCPointerCast:
  2903. case CK_BlockPointerToObjCPointerCast:
  2904. case CK_NoOp:
  2905. case CK_LValueToRValue:
  2906. return EmitLValue(E->getSubExpr());
  2907. case CK_UncheckedDerivedToBase:
  2908. case CK_DerivedToBase: {
  2909. const RecordType *DerivedClassTy =
  2910. E->getSubExpr()->getType()->getAs<RecordType>();
  2911. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2912. LValue LV = EmitLValue(E->getSubExpr());
  2913. llvm::Value *This = LV.getAddress();
  2914. // Perform the derived-to-base conversion
  2915. llvm::Value *Base = GetAddressOfBaseClass(
  2916. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  2917. /*NullCheckValue=*/false, E->getExprLoc());
  2918. return MakeAddrLValue(Base, E->getType());
  2919. }
  2920. case CK_ToUnion:
  2921. return EmitAggExprToLValue(E);
  2922. case CK_BaseToDerived: {
  2923. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  2924. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2925. LValue LV = EmitLValue(E->getSubExpr());
  2926. // Perform the base-to-derived conversion
  2927. llvm::Value *Derived =
  2928. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  2929. E->path_begin(), E->path_end(),
  2930. /*NullCheckValue=*/false);
  2931. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  2932. // performed and the object is not of the derived type.
  2933. if (sanitizePerformTypeCheck())
  2934. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  2935. Derived, E->getType());
  2936. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  2937. EmitVTablePtrCheckForCast(E->getType(), Derived, /*MayBeNull=*/false,
  2938. CFITCK_DerivedCast, E->getLocStart());
  2939. return MakeAddrLValue(Derived, E->getType());
  2940. }
  2941. case CK_LValueBitCast: {
  2942. // This must be a reinterpret_cast (or c-style equivalent).
  2943. const auto *CE = cast<ExplicitCastExpr>(E);
  2944. LValue LV = EmitLValue(E->getSubExpr());
  2945. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2946. ConvertType(CE->getTypeAsWritten()));
  2947. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  2948. EmitVTablePtrCheckForCast(E->getType(), V, /*MayBeNull=*/false,
  2949. CFITCK_UnrelatedCast, E->getLocStart());
  2950. return MakeAddrLValue(V, E->getType());
  2951. }
  2952. case CK_ObjCObjectLValueCast: {
  2953. LValue LV = EmitLValue(E->getSubExpr());
  2954. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2955. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2956. ConvertType(ToType));
  2957. return MakeAddrLValue(V, E->getType());
  2958. }
  2959. // HLSL Change Starts
  2960. case CK_HLSLVectorSplat: {
  2961. LValue LV = EmitLValue(E->getSubExpr());
  2962. llvm::Value *LVal = nullptr;
  2963. if (LV.isSimple())
  2964. LVal = LV.getAddress();
  2965. else if (LV.isExtVectorElt()) {
  2966. llvm::Constant *VecElts = LV.getExtVectorElts();
  2967. LVal = Builder.CreateGEP(
  2968. LV.getExtVectorAddr(),
  2969. {Builder.getInt32(0), VecElts->getAggregateElement((unsigned)0)});
  2970. } else
  2971. // TODO: make sure all cases are supported.
  2972. assert(0 && "not implement cases");
  2973. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2974. // bitcast to target type
  2975. llvm::Type *ResultType = ConvertType(ToType);
  2976. llvm::Value *bitcast = Builder.CreateBitCast(LVal, ResultType);
  2977. return MakeAddrLValue(bitcast, ToType);
  2978. }
  2979. case CK_HLSLVectorTruncationCast: {
  2980. LValue LV = EmitLValue(E->getSubExpr());
  2981. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2982. // bitcast to target type
  2983. llvm::Type *ResultType = ConvertType(ToType);
  2984. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  2985. return MakeAddrLValue(bitcast, ToType);
  2986. }
  2987. case CK_HLSLVectorToScalarCast: {
  2988. LValue LV = EmitLValue(E->getSubExpr());
  2989. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2990. llvm::ConstantInt *idxZero = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0);
  2991. llvm::Value *GEP = Builder.CreateInBoundsGEP(LV.getAddress(), {idxZero, idxZero});
  2992. return MakeAddrLValue(GEP, ToType);
  2993. } break;
  2994. case CK_HLSLCC_IntegralToFloating:
  2995. case CK_HLSLCC_FloatingToIntegral: {
  2996. LValue LV = EmitLValue(E->getSubExpr());
  2997. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2998. // bitcast to target type
  2999. llvm::Type *ResultType = ConvertType(ToType);
  3000. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  3001. return MakeAddrLValue(bitcast, ToType);
  3002. }
  3003. case CK_FlatConversion: {
  3004. // Just bitcast.
  3005. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3006. LValue LV = EmitLValue(E->getSubExpr());
  3007. llvm::Value *This = LV.getAddress();
  3008. // bitcast to target type
  3009. llvm::Type *ResultType = ConvertType(ToType);
  3010. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  3011. return MakeAddrLValue(bitcast, ToType);
  3012. }
  3013. case CK_HLSLDerivedToBase: {
  3014. // HLSL only single inheritance.
  3015. // Just GEP.
  3016. QualType ToType = getContext().getLValueReferenceType(E->getType());
  3017. LValue LV = EmitLValue(E->getSubExpr());
  3018. llvm::Value *This = LV.getAddress();
  3019. // gep to target type
  3020. llvm::Type *ResultType = ConvertType(ToType);
  3021. unsigned level = 0;
  3022. llvm::Type *ToTy = ResultType->getPointerElementType();
  3023. llvm::Type *FromTy = This->getType()->getPointerElementType();
  3024. // For empty struct, just bitcast.
  3025. if (!isa<llvm::StructType>(FromTy->getStructElementType(0))) {
  3026. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  3027. return MakeAddrLValue(bitcast, ToType);
  3028. }
  3029. while (ToTy != FromTy) {
  3030. FromTy = FromTy->getStructElementType(0);
  3031. ++level;
  3032. }
  3033. llvm::Value *zeroIdx = Builder.getInt32(0);
  3034. SmallVector<llvm::Value *, 2> IdxList(level + 1, zeroIdx);
  3035. llvm::Value *GEP = Builder.CreateInBoundsGEP(This, IdxList);
  3036. return MakeAddrLValue(GEP, ToType);
  3037. }
  3038. // HLSL Change Ends
  3039. case CK_ZeroToOCLEvent:
  3040. llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
  3041. }
  3042. llvm_unreachable("Unhandled lvalue cast kind?");
  3043. }
  3044. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  3045. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  3046. return getOpaqueLValueMapping(e);
  3047. }
  3048. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  3049. const FieldDecl *FD,
  3050. SourceLocation Loc) {
  3051. QualType FT = FD->getType();
  3052. LValue FieldLV = EmitLValueForField(LV, FD);
  3053. switch (getEvaluationKind(FT)) {
  3054. case TEK_Complex:
  3055. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  3056. case TEK_Aggregate:
  3057. return FieldLV.asAggregateRValue();
  3058. case TEK_Scalar:
  3059. return EmitLoadOfLValue(FieldLV, Loc);
  3060. }
  3061. llvm_unreachable("bad evaluation kind");
  3062. }
  3063. //===--------------------------------------------------------------------===//
  3064. // Expression Emission
  3065. //===--------------------------------------------------------------------===//
  3066. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3067. ReturnValueSlot ReturnValue) {
  3068. // Builtins never have block type.
  3069. if (E->getCallee()->getType()->isBlockPointerType())
  3070. return EmitBlockCallExpr(E, ReturnValue);
  3071. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3072. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3073. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3074. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3075. const Decl *TargetDecl = E->getCalleeDecl();
  3076. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  3077. if (unsigned builtinID = FD->getBuiltinID())
  3078. return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
  3079. // HLSL Change Starts
  3080. if (getLangOpts().HLSL) {
  3081. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(FD->getParent())) {
  3082. if (ns->getName() == "hlsl") {
  3083. // do hlsl intrinsic generation
  3084. return EmitHLSLBuiltinCallExpr(FD, E, ReturnValue);
  3085. }
  3086. }
  3087. }
  3088. // HLSL Change End
  3089. }
  3090. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3091. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
  3092. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3093. if (const auto *PseudoDtor =
  3094. dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
  3095. QualType DestroyedType = PseudoDtor->getDestroyedType();
  3096. if (getLangOpts().ObjCAutoRefCount &&
  3097. DestroyedType->isObjCLifetimeType() &&
  3098. (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  3099. DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
  3100. // Automatic Reference Counting:
  3101. // If the pseudo-expression names a retainable object with weak or
  3102. // strong lifetime, the object shall be released.
  3103. Expr *BaseExpr = PseudoDtor->getBase();
  3104. llvm::Value *BaseValue = nullptr;
  3105. Qualifiers BaseQuals;
  3106. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3107. if (PseudoDtor->isArrow()) {
  3108. BaseValue = EmitScalarExpr(BaseExpr);
  3109. const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
  3110. BaseQuals = PTy->getPointeeType().getQualifiers();
  3111. } else {
  3112. LValue BaseLV = EmitLValue(BaseExpr);
  3113. BaseValue = BaseLV.getAddress();
  3114. QualType BaseTy = BaseExpr->getType();
  3115. BaseQuals = BaseTy.getQualifiers();
  3116. }
  3117. switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
  3118. case Qualifiers::OCL_None:
  3119. case Qualifiers::OCL_ExplicitNone:
  3120. case Qualifiers::OCL_Autoreleasing:
  3121. break;
  3122. case Qualifiers::OCL_Strong:
  3123. EmitARCRelease(Builder.CreateLoad(BaseValue,
  3124. PseudoDtor->getDestroyedType().isVolatileQualified()),
  3125. ARCPreciseLifetime);
  3126. break;
  3127. case Qualifiers::OCL_Weak:
  3128. EmitARCDestroyWeak(BaseValue);
  3129. break;
  3130. }
  3131. } else {
  3132. // C++ [expr.pseudo]p1:
  3133. // The result shall only be used as the operand for the function call
  3134. // operator (), and the result of such a call has type void. The only
  3135. // effect is the evaluation of the postfix-expression before the dot or
  3136. // arrow.
  3137. EmitScalarExpr(E->getCallee());
  3138. }
  3139. return RValue::get(nullptr);
  3140. }
  3141. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  3142. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3143. TargetDecl);
  3144. }
  3145. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  3146. // Comma expressions just emit their LHS then their RHS as an l-value.
  3147. if (E->getOpcode() == BO_Comma) {
  3148. EmitIgnoredExpr(E->getLHS());
  3149. EnsureInsertPoint();
  3150. return EmitLValue(E->getRHS());
  3151. }
  3152. if (E->getOpcode() == BO_PtrMemD ||
  3153. E->getOpcode() == BO_PtrMemI)
  3154. return EmitPointerToDataMemberBinaryExpr(E);
  3155. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  3156. // Note that in all of these cases, __block variables need the RHS
  3157. // evaluated first just in case the variable gets moved by the RHS.
  3158. switch (getEvaluationKind(E->getType())) {
  3159. case TEK_Scalar: {
  3160. switch (E->getLHS()->getType().getObjCLifetime()) {
  3161. case Qualifiers::OCL_Strong:
  3162. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  3163. case Qualifiers::OCL_Autoreleasing:
  3164. return EmitARCStoreAutoreleasing(E).first;
  3165. // No reason to do any of these differently.
  3166. case Qualifiers::OCL_None:
  3167. case Qualifiers::OCL_ExplicitNone:
  3168. case Qualifiers::OCL_Weak:
  3169. break;
  3170. }
  3171. RValue RV = EmitAnyExpr(E->getRHS());
  3172. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  3173. EmitStoreThroughLValue(RV, LV);
  3174. return LV;
  3175. }
  3176. case TEK_Complex:
  3177. return EmitComplexAssignmentLValue(E);
  3178. case TEK_Aggregate:
  3179. return EmitAggExprToLValue(E);
  3180. }
  3181. llvm_unreachable("bad evaluation kind");
  3182. }
  3183. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  3184. RValue RV = EmitCallExpr(E);
  3185. if (!RV.isScalar())
  3186. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3187. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  3188. "Can't have a scalar return unless the return type is a "
  3189. "reference type!");
  3190. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3191. }
  3192. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  3193. // FIXME: This shouldn't require another copy.
  3194. return EmitAggExprToLValue(E);
  3195. }
  3196. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  3197. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  3198. && "binding l-value to type which needs a temporary");
  3199. AggValueSlot Slot = CreateAggTemp(E->getType());
  3200. EmitCXXConstructExpr(E, Slot);
  3201. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3202. }
  3203. LValue
  3204. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  3205. return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  3206. }
  3207. llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  3208. return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
  3209. ConvertType(E->getType())->getPointerTo());
  3210. }
  3211. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  3212. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
  3213. }
  3214. LValue
  3215. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  3216. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3217. Slot.setExternallyDestructed();
  3218. EmitAggExpr(E->getSubExpr(), Slot);
  3219. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
  3220. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3221. }
  3222. LValue
  3223. CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
  3224. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3225. EmitLambdaExpr(E, Slot);
  3226. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3227. }
  3228. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  3229. RValue RV = EmitObjCMessageExpr(E);
  3230. if (!RV.isScalar())
  3231. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3232. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  3233. "Can't have a scalar return unless the return type is a "
  3234. "reference type!");
  3235. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3236. }
  3237. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  3238. llvm::Value *V =
  3239. CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
  3240. return MakeAddrLValue(V, E->getType());
  3241. }
  3242. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  3243. const ObjCIvarDecl *Ivar) {
  3244. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  3245. }
  3246. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  3247. llvm::Value *BaseValue,
  3248. const ObjCIvarDecl *Ivar,
  3249. unsigned CVRQualifiers) {
  3250. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  3251. Ivar, CVRQualifiers);
  3252. }
  3253. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  3254. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  3255. llvm::Value *BaseValue = nullptr;
  3256. const Expr *BaseExpr = E->getBase();
  3257. Qualifiers BaseQuals;
  3258. QualType ObjectTy;
  3259. if (E->isArrow()) {
  3260. BaseValue = EmitScalarExpr(BaseExpr);
  3261. ObjectTy = BaseExpr->getType()->getPointeeType();
  3262. BaseQuals = ObjectTy.getQualifiers();
  3263. } else {
  3264. LValue BaseLV = EmitLValue(BaseExpr);
  3265. // FIXME: this isn't right for bitfields.
  3266. BaseValue = BaseLV.getAddress();
  3267. ObjectTy = BaseExpr->getType();
  3268. BaseQuals = ObjectTy.getQualifiers();
  3269. }
  3270. LValue LV =
  3271. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  3272. BaseQuals.getCVRQualifiers());
  3273. setObjCGCLValueClass(getContext(), E, LV);
  3274. return LV;
  3275. }
  3276. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  3277. // Can only get l-value for message expression returning aggregate type
  3278. RValue RV = EmitAnyExprToTemp(E);
  3279. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3280. }
  3281. RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
  3282. const CallExpr *E, ReturnValueSlot ReturnValue,
  3283. const Decl *TargetDecl, llvm::Value *Chain) {
  3284. // Get the actual function type. The callee type will always be a pointer to
  3285. // function type or a block pointer type.
  3286. assert(CalleeType->isFunctionPointerType() &&
  3287. "Call must have function pointer type!");
  3288. CalleeType = getContext().getCanonicalType(CalleeType);
  3289. const auto *FnType =
  3290. cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
  3291. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  3292. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  3293. if (llvm::Constant *PrefixSig =
  3294. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  3295. SanitizerScope SanScope(this);
  3296. llvm::Constant *FTRTTIConst =
  3297. CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
  3298. llvm::Type *PrefixStructTyElems[] = {
  3299. PrefixSig->getType(),
  3300. FTRTTIConst->getType()
  3301. };
  3302. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  3303. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  3304. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  3305. Callee, llvm::PointerType::getUnqual(PrefixStructTy));
  3306. llvm::Value *CalleeSigPtr =
  3307. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  3308. llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
  3309. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  3310. llvm::BasicBlock *Cont = createBasicBlock("cont");
  3311. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  3312. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  3313. EmitBlock(TypeCheck);
  3314. llvm::Value *CalleeRTTIPtr =
  3315. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  3316. llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
  3317. llvm::Value *CalleeRTTIMatch =
  3318. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  3319. llvm::Constant *StaticData[] = {
  3320. EmitCheckSourceLocation(E->getLocStart()),
  3321. EmitCheckTypeDescriptor(CalleeType)
  3322. };
  3323. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  3324. "function_type_mismatch", StaticData, Callee);
  3325. Builder.CreateBr(Cont);
  3326. EmitBlock(Cont);
  3327. }
  3328. }
  3329. // HLSL Change Begins
  3330. llvm::SmallVector<LValue, 8> castArgList;
  3331. // The argList of the CallExpr, may be update for out parameter
  3332. llvm::SmallVector<const Stmt *, 8> argList(E->arg_begin(), E->arg_end());
  3333. ConstExprIterator argBegin = argList.data();
  3334. ConstExprIterator argEnd = argList.data() + E->getNumArgs();
  3335. // out param conversion
  3336. CodeGenFunction::HLSLOutParamScope OutParamScope(*this);
  3337. auto MapTemp = [&](const VarDecl *LocalVD, llvm::Value *TmpArg) {
  3338. OutParamScope.addTemp(LocalVD, TmpArg);
  3339. };
  3340. if (getLangOpts().HLSL) {
  3341. if (const FunctionDecl *FD = E->getDirectCallee())
  3342. CGM.getHLSLRuntime().EmitHLSLOutParamConversionInit(*this, FD, E,
  3343. castArgList, argList, MapTemp);
  3344. }
  3345. // HLSL Change Ends
  3346. CallArgList Args;
  3347. if (Chain)
  3348. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  3349. CGM.getContext().VoidPtrTy);
  3350. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), argBegin, argEnd, // HLSL Change - use updated argList
  3351. E->getDirectCallee(), /*ParamsToSkip*/ 0);
  3352. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  3353. Args, FnType, /*isChainCall=*/Chain);
  3354. // C99 6.5.2.2p6:
  3355. // If the expression that denotes the called function has a type
  3356. // that does not include a prototype, [the default argument
  3357. // promotions are performed]. If the number of arguments does not
  3358. // equal the number of parameters, the behavior is undefined. If
  3359. // the function is defined with a type that includes a prototype,
  3360. // and either the prototype ends with an ellipsis (, ...) or the
  3361. // types of the arguments after promotion are not compatible with
  3362. // the types of the parameters, the behavior is undefined. If the
  3363. // function is defined with a type that does not include a
  3364. // prototype, and the types of the arguments after promotion are
  3365. // not compatible with those of the parameters after promotion,
  3366. // the behavior is undefined [except in some trivial cases].
  3367. // That is, in the general case, we should assume that a call
  3368. // through an unprototyped function type works like a *non-variadic*
  3369. // call. The way we make this work is to cast to the exact type
  3370. // of the promoted arguments.
  3371. //
  3372. // Chain calls use this same code path to add the invisible chain parameter
  3373. // to the function type.
  3374. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  3375. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  3376. CalleeTy = CalleeTy->getPointerTo();
  3377. Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
  3378. }
  3379. RValue CallVal = EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
  3380. // HLSL Change Begins
  3381. // out param conversion
  3382. // conversion and copy back after the call
  3383. if (getLangOpts().HLSL)
  3384. CGM.getHLSLRuntime().EmitHLSLOutParamConversionCopyBack(*this, castArgList);
  3385. // HLSL Change Ends
  3386. return CallVal;
  3387. }
  3388. LValue CodeGenFunction::
  3389. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  3390. llvm::Value *BaseV;
  3391. if (E->getOpcode() == BO_PtrMemI)
  3392. BaseV = EmitScalarExpr(E->getLHS());
  3393. else
  3394. BaseV = EmitLValue(E->getLHS()).getAddress();
  3395. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  3396. const MemberPointerType *MPT
  3397. = E->getRHS()->getType()->getAs<MemberPointerType>();
  3398. llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
  3399. *this, E, BaseV, OffsetV, MPT);
  3400. return MakeAddrLValue(AddV, MPT->getPointeeType());
  3401. }
  3402. /// Given the address of a temporary variable, produce an r-value of
  3403. /// its type.
  3404. RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
  3405. QualType type,
  3406. SourceLocation loc) {
  3407. LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
  3408. switch (getEvaluationKind(type)) {
  3409. case TEK_Complex:
  3410. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  3411. case TEK_Aggregate:
  3412. return lvalue.asAggregateRValue();
  3413. case TEK_Scalar:
  3414. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  3415. }
  3416. llvm_unreachable("bad evaluation kind");
  3417. }
  3418. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  3419. assert(Val->getType()->isFPOrFPVectorTy());
  3420. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  3421. return;
  3422. llvm::MDBuilder MDHelper(getLLVMContext());
  3423. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  3424. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  3425. }
  3426. namespace {
  3427. struct LValueOrRValue {
  3428. LValue LV;
  3429. RValue RV;
  3430. };
  3431. }
  3432. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  3433. const PseudoObjectExpr *E,
  3434. bool forLValue,
  3435. AggValueSlot slot) {
  3436. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  3437. // Find the result expression, if any.
  3438. const Expr *resultExpr = E->getResultExpr();
  3439. LValueOrRValue result;
  3440. for (PseudoObjectExpr::const_semantics_iterator
  3441. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  3442. const Expr *semantic = *i;
  3443. // If this semantic expression is an opaque value, bind it
  3444. // to the result of its source expression.
  3445. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  3446. // If this is the result expression, we may need to evaluate
  3447. // directly into the slot.
  3448. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  3449. OVMA opaqueData;
  3450. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  3451. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  3452. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  3453. LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
  3454. opaqueData = OVMA::bind(CGF, ov, LV);
  3455. result.RV = slot.asRValue();
  3456. // Otherwise, emit as normal.
  3457. } else {
  3458. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  3459. // If this is the result, also evaluate the result now.
  3460. if (ov == resultExpr) {
  3461. if (forLValue)
  3462. result.LV = CGF.EmitLValue(ov);
  3463. else
  3464. result.RV = CGF.EmitAnyExpr(ov, slot);
  3465. }
  3466. }
  3467. opaques.push_back(opaqueData);
  3468. // Otherwise, if the expression is the result, evaluate it
  3469. // and remember the result.
  3470. } else if (semantic == resultExpr) {
  3471. if (forLValue)
  3472. result.LV = CGF.EmitLValue(semantic);
  3473. else
  3474. result.RV = CGF.EmitAnyExpr(semantic, slot);
  3475. // Otherwise, evaluate the expression in an ignored context.
  3476. } else {
  3477. CGF.EmitIgnoredExpr(semantic);
  3478. }
  3479. }
  3480. // Unbind all the opaques now.
  3481. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  3482. opaques[i].unbind(CGF);
  3483. return result;
  3484. }
  3485. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  3486. AggValueSlot slot) {
  3487. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  3488. }
  3489. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  3490. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  3491. }