CodeGenFunction.h 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  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 is the internal per-function state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGLoopInfo.h"
  18. #include "CGValue.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "EHScopeStack.h"
  22. #include "VarBypassDetector.h"
  23. #include "clang/AST/CharUnits.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/ExprOpenMP.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/ABI.h"
  29. #include "clang/Basic/CapturedStmt.h"
  30. #include "clang/Basic/OpenMPKinds.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Frontend/CodeGenOptions.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/DenseMap.h"
  35. #include "llvm/ADT/MapVector.h"
  36. #include "llvm/ADT/SmallVector.h"
  37. #include "llvm/IR/ValueHandle.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Transforms/Utils/SanitizerStats.h"
  40. namespace llvm {
  41. class BasicBlock;
  42. class LLVMContext;
  43. class MDNode;
  44. class Module;
  45. class SwitchInst;
  46. class Twine;
  47. class Value;
  48. class CallSite;
  49. }
  50. namespace clang {
  51. class ASTContext;
  52. class BlockDecl;
  53. class CXXDestructorDecl;
  54. class CXXForRangeStmt;
  55. class CXXTryStmt;
  56. class Decl;
  57. class LabelDecl;
  58. class EnumConstantDecl;
  59. class FunctionDecl;
  60. class FunctionProtoType;
  61. class LabelStmt;
  62. class ObjCContainerDecl;
  63. class ObjCInterfaceDecl;
  64. class ObjCIvarDecl;
  65. class ObjCMethodDecl;
  66. class ObjCImplementationDecl;
  67. class ObjCPropertyImplDecl;
  68. class TargetInfo;
  69. class VarDecl;
  70. class ObjCForCollectionStmt;
  71. class ObjCAtTryStmt;
  72. class ObjCAtThrowStmt;
  73. class ObjCAtSynchronizedStmt;
  74. class ObjCAutoreleasePoolStmt;
  75. namespace analyze_os_log {
  76. class OSLogBufferLayout;
  77. }
  78. namespace CodeGen {
  79. class CodeGenTypes;
  80. class CGCallee;
  81. class CGFunctionInfo;
  82. class CGRecordLayout;
  83. class CGBlockInfo;
  84. class CGCXXABI;
  85. class BlockByrefHelpers;
  86. class BlockByrefInfo;
  87. class BlockFlags;
  88. class BlockFieldFlags;
  89. class RegionCodeGenTy;
  90. class TargetCodeGenInfo;
  91. struct OMPTaskDataTy;
  92. struct CGCoroData;
  93. /// The kind of evaluation to perform on values of a particular
  94. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  95. /// CGExprAgg?
  96. ///
  97. /// TODO: should vectors maybe be split out into their own thing?
  98. enum TypeEvaluationKind {
  99. TEK_Scalar,
  100. TEK_Complex,
  101. TEK_Aggregate
  102. };
  103. #define LIST_SANITIZER_CHECKS \
  104. SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
  105. SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
  106. SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
  107. SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
  108. SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
  109. SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
  110. SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
  111. SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
  112. SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
  113. SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
  114. SANITIZER_CHECK(MissingReturn, missing_return, 0) \
  115. SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
  116. SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
  117. SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
  118. SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
  119. SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
  120. SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
  121. SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
  122. SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
  123. SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
  124. SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
  125. SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
  126. SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
  127. enum SanitizerHandler {
  128. #define SANITIZER_CHECK(Enum, Name, Version) Enum,
  129. LIST_SANITIZER_CHECKS
  130. #undef SANITIZER_CHECK
  131. };
  132. /// Helper class with most of the code for saving a value for a
  133. /// conditional expression cleanup.
  134. struct DominatingLLVMValue {
  135. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  136. /// Answer whether the given value needs extra work to be saved.
  137. static bool needsSaving(llvm::Value *value) {
  138. // If it's not an instruction, we don't need to save.
  139. if (!isa<llvm::Instruction>(value)) return false;
  140. // If it's an instruction in the entry block, we don't need to save.
  141. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  142. return (block != &block->getParent()->getEntryBlock());
  143. }
  144. static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
  145. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
  146. };
  147. /// A partial specialization of DominatingValue for llvm::Values that
  148. /// might be llvm::Instructions.
  149. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  150. typedef T *type;
  151. static type restore(CodeGenFunction &CGF, saved_type value) {
  152. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  153. }
  154. };
  155. /// A specialization of DominatingValue for Address.
  156. template <> struct DominatingValue<Address> {
  157. typedef Address type;
  158. struct saved_type {
  159. DominatingLLVMValue::saved_type SavedValue;
  160. CharUnits Alignment;
  161. };
  162. static bool needsSaving(type value) {
  163. return DominatingLLVMValue::needsSaving(value.getPointer());
  164. }
  165. static saved_type save(CodeGenFunction &CGF, type value) {
  166. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  167. value.getAlignment() };
  168. }
  169. static type restore(CodeGenFunction &CGF, saved_type value) {
  170. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  171. value.Alignment);
  172. }
  173. };
  174. /// A specialization of DominatingValue for RValue.
  175. template <> struct DominatingValue<RValue> {
  176. typedef RValue type;
  177. class saved_type {
  178. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  179. AggregateAddress, ComplexAddress };
  180. llvm::Value *Value;
  181. unsigned K : 3;
  182. unsigned Align : 29;
  183. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  184. : Value(v), K(k), Align(a) {}
  185. public:
  186. static bool needsSaving(RValue value);
  187. static saved_type save(CodeGenFunction &CGF, RValue value);
  188. RValue restore(CodeGenFunction &CGF);
  189. // implementations in CGCleanup.cpp
  190. };
  191. static bool needsSaving(type value) {
  192. return saved_type::needsSaving(value);
  193. }
  194. static saved_type save(CodeGenFunction &CGF, type value) {
  195. return saved_type::save(CGF, value);
  196. }
  197. static type restore(CodeGenFunction &CGF, saved_type value) {
  198. return value.restore(CGF);
  199. }
  200. };
  201. /// CodeGenFunction - This class organizes the per-function state that is used
  202. /// while generating LLVM code.
  203. class CodeGenFunction : public CodeGenTypeCache {
  204. CodeGenFunction(const CodeGenFunction &) = delete;
  205. void operator=(const CodeGenFunction &) = delete;
  206. friend class CGCXXABI;
  207. public:
  208. /// A jump destination is an abstract label, branching to which may
  209. /// require a jump out through normal cleanups.
  210. struct JumpDest {
  211. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  212. JumpDest(llvm::BasicBlock *Block,
  213. EHScopeStack::stable_iterator Depth,
  214. unsigned Index)
  215. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  216. bool isValid() const { return Block != nullptr; }
  217. llvm::BasicBlock *getBlock() const { return Block; }
  218. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  219. unsigned getDestIndex() const { return Index; }
  220. // This should be used cautiously.
  221. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  222. ScopeDepth = depth;
  223. }
  224. private:
  225. llvm::BasicBlock *Block;
  226. EHScopeStack::stable_iterator ScopeDepth;
  227. unsigned Index;
  228. };
  229. CodeGenModule &CGM; // Per-module state.
  230. const TargetInfo &Target;
  231. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  232. LoopInfoStack LoopStack;
  233. CGBuilderTy Builder;
  234. // Stores variables for which we can't generate correct lifetime markers
  235. // because of jumps.
  236. VarBypassDetector Bypasses;
  237. // CodeGen lambda for loops and support for ordered clause
  238. typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
  239. JumpDest)>
  240. CodeGenLoopTy;
  241. typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
  242. const unsigned, const bool)>
  243. CodeGenOrderedTy;
  244. // Codegen lambda for loop bounds in worksharing loop constructs
  245. typedef llvm::function_ref<std::pair<LValue, LValue>(
  246. CodeGenFunction &, const OMPExecutableDirective &S)>
  247. CodeGenLoopBoundsTy;
  248. // Codegen lambda for loop bounds in dispatch-based loop implementation
  249. typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
  250. CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
  251. Address UB)>
  252. CodeGenDispatchBoundsTy;
  253. /// CGBuilder insert helper. This function is called after an
  254. /// instruction is created using Builder.
  255. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  256. llvm::BasicBlock *BB,
  257. llvm::BasicBlock::iterator InsertPt) const;
  258. /// CurFuncDecl - Holds the Decl for the current outermost
  259. /// non-closure context.
  260. const Decl *CurFuncDecl;
  261. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  262. const Decl *CurCodeDecl;
  263. const CGFunctionInfo *CurFnInfo;
  264. QualType FnRetTy;
  265. llvm::Function *CurFn = nullptr;
  266. // Holds coroutine data if the current function is a coroutine. We use a
  267. // wrapper to manage its lifetime, so that we don't have to define CGCoroData
  268. // in this header.
  269. struct CGCoroInfo {
  270. std::unique_ptr<CGCoroData> Data;
  271. CGCoroInfo();
  272. ~CGCoroInfo();
  273. };
  274. CGCoroInfo CurCoro;
  275. bool isCoroutine() const {
  276. return CurCoro.Data != nullptr;
  277. }
  278. /// CurGD - The GlobalDecl for the current function being compiled.
  279. GlobalDecl CurGD;
  280. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  281. /// cleanups associated with the parameters.
  282. EHScopeStack::stable_iterator PrologueCleanupDepth;
  283. /// ReturnBlock - Unified return block.
  284. JumpDest ReturnBlock;
  285. /// ReturnValue - The temporary alloca to hold the return
  286. /// value. This is invalid iff the function has no return value.
  287. Address ReturnValue = Address::invalid();
  288. /// Return true if a label was seen in the current scope.
  289. bool hasLabelBeenSeenInCurrentScope() const {
  290. if (CurLexicalScope)
  291. return CurLexicalScope->hasLabels();
  292. return !LabelMap.empty();
  293. }
  294. /// AllocaInsertPoint - This is an instruction in the entry block before which
  295. /// we prefer to insert allocas.
  296. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  297. /// API for captured statement code generation.
  298. class CGCapturedStmtInfo {
  299. public:
  300. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  301. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  302. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  303. CapturedRegionKind K = CR_Default)
  304. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  305. RecordDecl::field_iterator Field =
  306. S.getCapturedRecordDecl()->field_begin();
  307. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  308. E = S.capture_end();
  309. I != E; ++I, ++Field) {
  310. if (I->capturesThis())
  311. CXXThisFieldDecl = *Field;
  312. else if (I->capturesVariable())
  313. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  314. else if (I->capturesVariableByCopy())
  315. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  316. }
  317. }
  318. virtual ~CGCapturedStmtInfo();
  319. CapturedRegionKind getKind() const { return Kind; }
  320. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  321. // Retrieve the value of the context parameter.
  322. virtual llvm::Value *getContextValue() const { return ThisValue; }
  323. /// Lookup the captured field decl for a variable.
  324. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  325. return CaptureFields.lookup(VD->getCanonicalDecl());
  326. }
  327. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  328. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  329. static bool classof(const CGCapturedStmtInfo *) {
  330. return true;
  331. }
  332. /// Emit the captured statement body.
  333. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  334. CGF.incrementProfileCounter(S);
  335. CGF.EmitStmt(S);
  336. }
  337. /// Get the name of the capture helper.
  338. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  339. private:
  340. /// The kind of captured statement being generated.
  341. CapturedRegionKind Kind;
  342. /// Keep the map between VarDecl and FieldDecl.
  343. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  344. /// The base address of the captured record, passed in as the first
  345. /// argument of the parallel region function.
  346. llvm::Value *ThisValue;
  347. /// Captured 'this' type.
  348. FieldDecl *CXXThisFieldDecl;
  349. };
  350. CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
  351. /// RAII for correct setting/restoring of CapturedStmtInfo.
  352. class CGCapturedStmtRAII {
  353. private:
  354. CodeGenFunction &CGF;
  355. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  356. public:
  357. CGCapturedStmtRAII(CodeGenFunction &CGF,
  358. CGCapturedStmtInfo *NewCapturedStmtInfo)
  359. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  360. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  361. }
  362. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  363. };
  364. /// An abstract representation of regular/ObjC call/message targets.
  365. class AbstractCallee {
  366. /// The function declaration of the callee.
  367. const Decl *CalleeDecl;
  368. public:
  369. AbstractCallee() : CalleeDecl(nullptr) {}
  370. AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
  371. AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
  372. bool hasFunctionDecl() const {
  373. return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
  374. }
  375. const Decl *getDecl() const { return CalleeDecl; }
  376. unsigned getNumParams() const {
  377. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  378. return FD->getNumParams();
  379. return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
  380. }
  381. const ParmVarDecl *getParamDecl(unsigned I) const {
  382. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  383. return FD->getParamDecl(I);
  384. return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
  385. }
  386. };
  387. /// Sanitizers enabled for this function.
  388. SanitizerSet SanOpts;
  389. /// True if CodeGen currently emits code implementing sanitizer checks.
  390. bool IsSanitizerScope = false;
  391. /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  392. class SanitizerScope {
  393. CodeGenFunction *CGF;
  394. public:
  395. SanitizerScope(CodeGenFunction *CGF);
  396. ~SanitizerScope();
  397. };
  398. /// In C++, whether we are code generating a thunk. This controls whether we
  399. /// should emit cleanups.
  400. bool CurFuncIsThunk = false;
  401. /// In ARC, whether we should autorelease the return value.
  402. bool AutoreleaseResult = false;
  403. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  404. /// potentially set the return value.
  405. bool SawAsmBlock = false;
  406. const NamedDecl *CurSEHParent = nullptr;
  407. /// True if the current function is an outlined SEH helper. This can be a
  408. /// finally block or filter expression.
  409. bool IsOutlinedSEHHelper = false;
  410. const CodeGen::CGBlockInfo *BlockInfo = nullptr;
  411. llvm::Value *BlockPointer = nullptr;
  412. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  413. FieldDecl *LambdaThisCaptureField = nullptr;
  414. /// A mapping from NRVO variables to the flags used to indicate
  415. /// when the NRVO has been applied to this variable.
  416. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  417. EHScopeStack EHStack;
  418. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  419. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  420. llvm::Instruction *CurrentFuncletPad = nullptr;
  421. class CallLifetimeEnd final : public EHScopeStack::Cleanup {
  422. llvm::Value *Addr;
  423. llvm::Value *Size;
  424. public:
  425. CallLifetimeEnd(Address addr, llvm::Value *size)
  426. : Addr(addr.getPointer()), Size(size) {}
  427. void Emit(CodeGenFunction &CGF, Flags flags) override {
  428. CGF.EmitLifetimeEnd(Size, Addr);
  429. }
  430. };
  431. /// Header for data within LifetimeExtendedCleanupStack.
  432. struct LifetimeExtendedCleanupHeader {
  433. /// The size of the following cleanup object.
  434. unsigned Size;
  435. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  436. unsigned Kind : 31;
  437. /// Whether this is a conditional cleanup.
  438. unsigned IsConditional : 1;
  439. size_t getSize() const { return Size; }
  440. CleanupKind getKind() const { return (CleanupKind)Kind; }
  441. bool isConditional() const { return IsConditional; }
  442. };
  443. /// i32s containing the indexes of the cleanup destinations.
  444. Address NormalCleanupDest = Address::invalid();
  445. unsigned NextCleanupDestIndex = 1;
  446. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  447. CGBlockInfo *FirstBlockInfo = nullptr;
  448. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  449. llvm::BasicBlock *EHResumeBlock = nullptr;
  450. /// The exception slot. All landing pads write the current exception pointer
  451. /// into this alloca.
  452. llvm::Value *ExceptionSlot = nullptr;
  453. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  454. /// write the current selector value into this alloca.
  455. llvm::AllocaInst *EHSelectorSlot = nullptr;
  456. /// A stack of exception code slots. Entering an __except block pushes a slot
  457. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  458. /// a value from the top of the stack.
  459. SmallVector<Address, 1> SEHCodeSlotStack;
  460. /// Value returned by __exception_info intrinsic.
  461. llvm::Value *SEHInfo = nullptr;
  462. /// Emits a landing pad for the current EH stack.
  463. llvm::BasicBlock *EmitLandingPad();
  464. llvm::BasicBlock *getInvokeDestImpl();
  465. template <class T>
  466. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  467. return DominatingValue<T>::save(*this, value);
  468. }
  469. public:
  470. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  471. /// rethrows.
  472. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  473. /// A class controlling the emission of a finally block.
  474. class FinallyInfo {
  475. /// Where the catchall's edge through the cleanup should go.
  476. JumpDest RethrowDest;
  477. /// A function to call to enter the catch.
  478. llvm::Constant *BeginCatchFn;
  479. /// An i1 variable indicating whether or not the @finally is
  480. /// running for an exception.
  481. llvm::AllocaInst *ForEHVar;
  482. /// An i8* variable into which the exception pointer to rethrow
  483. /// has been saved.
  484. llvm::AllocaInst *SavedExnVar;
  485. public:
  486. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  487. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  488. llvm::Constant *rethrowFn);
  489. void exit(CodeGenFunction &CGF);
  490. };
  491. /// Returns true inside SEH __try blocks.
  492. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  493. /// Returns true while emitting a cleanuppad.
  494. bool isCleanupPadScope() const {
  495. return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
  496. }
  497. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  498. /// current full-expression. Safe against the possibility that
  499. /// we're currently inside a conditionally-evaluated expression.
  500. template <class T, class... As>
  501. void pushFullExprCleanup(CleanupKind kind, As... A) {
  502. // If we're not in a conditional branch, or if none of the
  503. // arguments requires saving, then use the unconditional cleanup.
  504. if (!isInConditionalBranch())
  505. return EHStack.pushCleanup<T>(kind, A...);
  506. // Stash values in a tuple so we can guarantee the order of saves.
  507. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  508. SavedTuple Saved{saveValueInCond(A)...};
  509. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  510. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  511. initFullExprCleanup();
  512. }
  513. /// Queue a cleanup to be pushed after finishing the current
  514. /// full-expression.
  515. template <class T, class... As>
  516. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  517. if (!isInConditionalBranch())
  518. return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...);
  519. Address ActiveFlag = createCleanupActiveFlag();
  520. assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
  521. "cleanup active flag should never need saving");
  522. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  523. SavedTuple Saved{saveValueInCond(A)...};
  524. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  525. pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved);
  526. }
  527. template <class T, class... As>
  528. void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag,
  529. As... A) {
  530. LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
  531. ActiveFlag.isValid()};
  532. size_t OldSize = LifetimeExtendedCleanupStack.size();
  533. LifetimeExtendedCleanupStack.resize(
  534. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
  535. (Header.IsConditional ? sizeof(ActiveFlag) : 0));
  536. static_assert(sizeof(Header) % alignof(T) == 0,
  537. "Cleanup will be allocated on misaligned address");
  538. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  539. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  540. new (Buffer + sizeof(Header)) T(A...);
  541. if (Header.IsConditional)
  542. new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
  543. }
  544. /// Set up the last cleanup that was pushed as a conditional
  545. /// full-expression cleanup.
  546. void initFullExprCleanup() {
  547. initFullExprCleanupWithFlag(createCleanupActiveFlag());
  548. }
  549. void initFullExprCleanupWithFlag(Address ActiveFlag);
  550. Address createCleanupActiveFlag();
  551. /// PushDestructorCleanup - Push a cleanup to call the
  552. /// complete-object destructor of an object of the given type at the
  553. /// given address. Does nothing if T is not a C++ class type with a
  554. /// non-trivial destructor.
  555. void PushDestructorCleanup(QualType T, Address Addr);
  556. /// PushDestructorCleanup - Push a cleanup to call the
  557. /// complete-object variant of the given destructor on the object at
  558. /// the given address.
  559. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
  560. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  561. /// process all branch fixups.
  562. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  563. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  564. /// The block cannot be reactivated. Pops it if it's the top of the
  565. /// stack.
  566. ///
  567. /// \param DominatingIP - An instruction which is known to
  568. /// dominate the current IP (if set) and which lies along
  569. /// all paths of execution between the current IP and the
  570. /// the point at which the cleanup comes into scope.
  571. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  572. llvm::Instruction *DominatingIP);
  573. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  574. /// Cannot be used to resurrect a deactivated cleanup.
  575. ///
  576. /// \param DominatingIP - An instruction which is known to
  577. /// dominate the current IP (if set) and which lies along
  578. /// all paths of execution between the current IP and the
  579. /// the point at which the cleanup comes into scope.
  580. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  581. llvm::Instruction *DominatingIP);
  582. /// Enters a new scope for capturing cleanups, all of which
  583. /// will be executed once the scope is exited.
  584. class RunCleanupsScope {
  585. EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
  586. size_t LifetimeExtendedCleanupStackSize;
  587. bool OldDidCallStackSave;
  588. protected:
  589. bool PerformCleanup;
  590. private:
  591. RunCleanupsScope(const RunCleanupsScope &) = delete;
  592. void operator=(const RunCleanupsScope &) = delete;
  593. protected:
  594. CodeGenFunction& CGF;
  595. public:
  596. /// Enter a new cleanup scope.
  597. explicit RunCleanupsScope(CodeGenFunction &CGF)
  598. : PerformCleanup(true), CGF(CGF)
  599. {
  600. CleanupStackDepth = CGF.EHStack.stable_begin();
  601. LifetimeExtendedCleanupStackSize =
  602. CGF.LifetimeExtendedCleanupStack.size();
  603. OldDidCallStackSave = CGF.DidCallStackSave;
  604. CGF.DidCallStackSave = false;
  605. OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
  606. CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
  607. }
  608. /// Exit this cleanup scope, emitting any accumulated cleanups.
  609. ~RunCleanupsScope() {
  610. if (PerformCleanup)
  611. ForceCleanup();
  612. }
  613. /// Determine whether this scope requires any cleanups.
  614. bool requiresCleanups() const {
  615. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  616. }
  617. /// Force the emission of cleanups now, instead of waiting
  618. /// until this object is destroyed.
  619. /// \param ValuesToReload - A list of values that need to be available at
  620. /// the insertion point after cleanup emission. If cleanup emission created
  621. /// a shared cleanup block, these value pointers will be rewritten.
  622. /// Otherwise, they not will be modified.
  623. void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
  624. assert(PerformCleanup && "Already forced cleanup");
  625. CGF.DidCallStackSave = OldDidCallStackSave;
  626. CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
  627. ValuesToReload);
  628. PerformCleanup = false;
  629. CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
  630. }
  631. };
  632. // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
  633. EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
  634. EHScopeStack::stable_end();
  635. class LexicalScope : public RunCleanupsScope {
  636. SourceRange Range;
  637. SmallVector<const LabelDecl*, 4> Labels;
  638. LexicalScope *ParentScope;
  639. LexicalScope(const LexicalScope &) = delete;
  640. void operator=(const LexicalScope &) = delete;
  641. public:
  642. /// Enter a new cleanup scope.
  643. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  644. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  645. CGF.CurLexicalScope = this;
  646. if (CGDebugInfo *DI = CGF.getDebugInfo())
  647. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  648. }
  649. void addLabel(const LabelDecl *label) {
  650. assert(PerformCleanup && "adding label to dead scope?");
  651. Labels.push_back(label);
  652. }
  653. /// Exit this cleanup scope, emitting any accumulated
  654. /// cleanups.
  655. ~LexicalScope() {
  656. if (CGDebugInfo *DI = CGF.getDebugInfo())
  657. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  658. // If we should perform a cleanup, force them now. Note that
  659. // this ends the cleanup scope before rescoping any labels.
  660. if (PerformCleanup) {
  661. ApplyDebugLocation DL(CGF, Range.getEnd(), true /* ImplicitCode */);
  662. ForceCleanup();
  663. }
  664. }
  665. /// Force the emission of cleanups now, instead of waiting
  666. /// until this object is destroyed.
  667. void ForceCleanup() {
  668. CGF.CurLexicalScope = ParentScope;
  669. RunCleanupsScope::ForceCleanup();
  670. if (!Labels.empty())
  671. rescopeLabels();
  672. }
  673. bool hasLabels() const {
  674. return !Labels.empty();
  675. }
  676. void rescopeLabels();
  677. };
  678. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  679. /// The class used to assign some variables some temporarily addresses.
  680. class OMPMapVars {
  681. DeclMapTy SavedLocals;
  682. DeclMapTy SavedTempAddresses;
  683. OMPMapVars(const OMPMapVars &) = delete;
  684. void operator=(const OMPMapVars &) = delete;
  685. public:
  686. explicit OMPMapVars() = default;
  687. ~OMPMapVars() {
  688. assert(SavedLocals.empty() && "Did not restored original addresses.");
  689. };
  690. /// Sets the address of the variable \p LocalVD to be \p TempAddr in
  691. /// function \p CGF.
  692. /// \return true if at least one variable was set already, false otherwise.
  693. bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
  694. Address TempAddr) {
  695. LocalVD = LocalVD->getCanonicalDecl();
  696. // Only save it once.
  697. if (SavedLocals.count(LocalVD)) return false;
  698. // Copy the existing local entry to SavedLocals.
  699. auto it = CGF.LocalDeclMap.find(LocalVD);
  700. if (it != CGF.LocalDeclMap.end())
  701. SavedLocals.try_emplace(LocalVD, it->second);
  702. else
  703. SavedLocals.try_emplace(LocalVD, Address::invalid());
  704. // Generate the private entry.
  705. QualType VarTy = LocalVD->getType();
  706. if (VarTy->isReferenceType()) {
  707. Address Temp = CGF.CreateMemTemp(VarTy);
  708. CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
  709. TempAddr = Temp;
  710. }
  711. SavedTempAddresses.try_emplace(LocalVD, TempAddr);
  712. return true;
  713. }
  714. /// Applies new addresses to the list of the variables.
  715. /// \return true if at least one variable is using new address, false
  716. /// otherwise.
  717. bool apply(CodeGenFunction &CGF) {
  718. copyInto(SavedTempAddresses, CGF.LocalDeclMap);
  719. SavedTempAddresses.clear();
  720. return !SavedLocals.empty();
  721. }
  722. /// Restores original addresses of the variables.
  723. void restore(CodeGenFunction &CGF) {
  724. if (!SavedLocals.empty()) {
  725. copyInto(SavedLocals, CGF.LocalDeclMap);
  726. SavedLocals.clear();
  727. }
  728. }
  729. private:
  730. /// Copy all the entries in the source map over the corresponding
  731. /// entries in the destination, which must exist.
  732. static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
  733. for (auto &Pair : Src) {
  734. if (!Pair.second.isValid()) {
  735. Dest.erase(Pair.first);
  736. continue;
  737. }
  738. auto I = Dest.find(Pair.first);
  739. if (I != Dest.end())
  740. I->second = Pair.second;
  741. else
  742. Dest.insert(Pair);
  743. }
  744. }
  745. };
  746. /// The scope used to remap some variables as private in the OpenMP loop body
  747. /// (or other captured region emitted without outlining), and to restore old
  748. /// vars back on exit.
  749. class OMPPrivateScope : public RunCleanupsScope {
  750. OMPMapVars MappedVars;
  751. OMPPrivateScope(const OMPPrivateScope &) = delete;
  752. void operator=(const OMPPrivateScope &) = delete;
  753. public:
  754. /// Enter a new OpenMP private scope.
  755. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  756. /// Registers \p LocalVD variable as a private and apply \p PrivateGen
  757. /// function for it to generate corresponding private variable. \p
  758. /// PrivateGen returns an address of the generated private variable.
  759. /// \return true if the variable is registered as private, false if it has
  760. /// been privatized already.
  761. bool addPrivate(const VarDecl *LocalVD,
  762. const llvm::function_ref<Address()> PrivateGen) {
  763. assert(PerformCleanup && "adding private to dead scope");
  764. return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
  765. }
  766. /// Privatizes local variables previously registered as private.
  767. /// Registration is separate from the actual privatization to allow
  768. /// initializers use values of the original variables, not the private one.
  769. /// This is important, for example, if the private variable is a class
  770. /// variable initialized by a constructor that references other private
  771. /// variables. But at initialization original variables must be used, not
  772. /// private copies.
  773. /// \return true if at least one variable was privatized, false otherwise.
  774. bool Privatize() { return MappedVars.apply(CGF); }
  775. void ForceCleanup() {
  776. RunCleanupsScope::ForceCleanup();
  777. MappedVars.restore(CGF);
  778. }
  779. /// Exit scope - all the mapped variables are restored.
  780. ~OMPPrivateScope() {
  781. if (PerformCleanup)
  782. ForceCleanup();
  783. }
  784. /// Checks if the global variable is captured in current function.
  785. bool isGlobalVarCaptured(const VarDecl *VD) const {
  786. VD = VD->getCanonicalDecl();
  787. return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
  788. }
  789. };
  790. /// Takes the old cleanup stack size and emits the cleanup blocks
  791. /// that have been added.
  792. void
  793. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  794. std::initializer_list<llvm::Value **> ValuesToReload = {});
  795. /// Takes the old cleanup stack size and emits the cleanup blocks
  796. /// that have been added, then adds all lifetime-extended cleanups from
  797. /// the given position to the stack.
  798. void
  799. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  800. size_t OldLifetimeExtendedStackSize,
  801. std::initializer_list<llvm::Value **> ValuesToReload = {});
  802. void ResolveBranchFixups(llvm::BasicBlock *Target);
  803. /// The given basic block lies in the current EH scope, but may be a
  804. /// target of a potentially scope-crossing jump; get a stable handle
  805. /// to which we can perform this jump later.
  806. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  807. return JumpDest(Target,
  808. EHStack.getInnermostNormalCleanup(),
  809. NextCleanupDestIndex++);
  810. }
  811. /// The given basic block lies in the current EH scope, but may be a
  812. /// target of a potentially scope-crossing jump; get a stable handle
  813. /// to which we can perform this jump later.
  814. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  815. return getJumpDestInCurrentScope(createBasicBlock(Name));
  816. }
  817. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  818. /// block through the normal cleanup handling code (if any) and then
  819. /// on to \arg Dest.
  820. void EmitBranchThroughCleanup(JumpDest Dest);
  821. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  822. /// specified destination obviously has no cleanups to run. 'false' is always
  823. /// a conservatively correct answer for this method.
  824. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  825. /// popCatchScope - Pops the catch scope at the top of the EHScope
  826. /// stack, emitting any required code (other than the catch handlers
  827. /// themselves).
  828. void popCatchScope();
  829. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  830. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  831. llvm::BasicBlock *
  832. getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
  833. /// An object to manage conditionally-evaluated expressions.
  834. class ConditionalEvaluation {
  835. llvm::BasicBlock *StartBB;
  836. public:
  837. ConditionalEvaluation(CodeGenFunction &CGF)
  838. : StartBB(CGF.Builder.GetInsertBlock()) {}
  839. void begin(CodeGenFunction &CGF) {
  840. assert(CGF.OutermostConditional != this);
  841. if (!CGF.OutermostConditional)
  842. CGF.OutermostConditional = this;
  843. }
  844. void end(CodeGenFunction &CGF) {
  845. assert(CGF.OutermostConditional != nullptr);
  846. if (CGF.OutermostConditional == this)
  847. CGF.OutermostConditional = nullptr;
  848. }
  849. /// Returns a block which will be executed prior to each
  850. /// evaluation of the conditional code.
  851. llvm::BasicBlock *getStartingBlock() const {
  852. return StartBB;
  853. }
  854. };
  855. /// isInConditionalBranch - Return true if we're currently emitting
  856. /// one branch or the other of a conditional expression.
  857. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  858. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  859. assert(isInConditionalBranch());
  860. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  861. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  862. store->setAlignment(addr.getAlignment().getQuantity());
  863. }
  864. /// An RAII object to record that we're evaluating a statement
  865. /// expression.
  866. class StmtExprEvaluation {
  867. CodeGenFunction &CGF;
  868. /// We have to save the outermost conditional: cleanups in a
  869. /// statement expression aren't conditional just because the
  870. /// StmtExpr is.
  871. ConditionalEvaluation *SavedOutermostConditional;
  872. public:
  873. StmtExprEvaluation(CodeGenFunction &CGF)
  874. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  875. CGF.OutermostConditional = nullptr;
  876. }
  877. ~StmtExprEvaluation() {
  878. CGF.OutermostConditional = SavedOutermostConditional;
  879. CGF.EnsureInsertPoint();
  880. }
  881. };
  882. /// An object which temporarily prevents a value from being
  883. /// destroyed by aggressive peephole optimizations that assume that
  884. /// all uses of a value have been realized in the IR.
  885. class PeepholeProtection {
  886. llvm::Instruction *Inst;
  887. friend class CodeGenFunction;
  888. public:
  889. PeepholeProtection() : Inst(nullptr) {}
  890. };
  891. /// A non-RAII class containing all the information about a bound
  892. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  893. /// this which makes individual mappings very simple; using this
  894. /// class directly is useful when you have a variable number of
  895. /// opaque values or don't want the RAII functionality for some
  896. /// reason.
  897. class OpaqueValueMappingData {
  898. const OpaqueValueExpr *OpaqueValue;
  899. bool BoundLValue;
  900. CodeGenFunction::PeepholeProtection Protection;
  901. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  902. bool boundLValue)
  903. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  904. public:
  905. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  906. static bool shouldBindAsLValue(const Expr *expr) {
  907. // gl-values should be bound as l-values for obvious reasons.
  908. // Records should be bound as l-values because IR generation
  909. // always keeps them in memory. Expressions of function type
  910. // act exactly like l-values but are formally required to be
  911. // r-values in C.
  912. return expr->isGLValue() ||
  913. expr->getType()->isFunctionType() ||
  914. hasAggregateEvaluationKind(expr->getType());
  915. }
  916. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  917. const OpaqueValueExpr *ov,
  918. const Expr *e) {
  919. if (shouldBindAsLValue(ov))
  920. return bind(CGF, ov, CGF.EmitLValue(e));
  921. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  922. }
  923. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  924. const OpaqueValueExpr *ov,
  925. const LValue &lv) {
  926. assert(shouldBindAsLValue(ov));
  927. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  928. return OpaqueValueMappingData(ov, true);
  929. }
  930. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  931. const OpaqueValueExpr *ov,
  932. const RValue &rv) {
  933. assert(!shouldBindAsLValue(ov));
  934. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  935. OpaqueValueMappingData data(ov, false);
  936. // Work around an extremely aggressive peephole optimization in
  937. // EmitScalarConversion which assumes that all other uses of a
  938. // value are extant.
  939. data.Protection = CGF.protectFromPeepholes(rv);
  940. return data;
  941. }
  942. bool isValid() const { return OpaqueValue != nullptr; }
  943. void clear() { OpaqueValue = nullptr; }
  944. void unbind(CodeGenFunction &CGF) {
  945. assert(OpaqueValue && "no data to unbind!");
  946. if (BoundLValue) {
  947. CGF.OpaqueLValues.erase(OpaqueValue);
  948. } else {
  949. CGF.OpaqueRValues.erase(OpaqueValue);
  950. CGF.unprotectFromPeepholes(Protection);
  951. }
  952. }
  953. };
  954. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  955. class OpaqueValueMapping {
  956. CodeGenFunction &CGF;
  957. OpaqueValueMappingData Data;
  958. public:
  959. static bool shouldBindAsLValue(const Expr *expr) {
  960. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  961. }
  962. /// Build the opaque value mapping for the given conditional
  963. /// operator if it's the GNU ?: extension. This is a common
  964. /// enough pattern that the convenience operator is really
  965. /// helpful.
  966. ///
  967. OpaqueValueMapping(CodeGenFunction &CGF,
  968. const AbstractConditionalOperator *op) : CGF(CGF) {
  969. if (isa<ConditionalOperator>(op))
  970. // Leave Data empty.
  971. return;
  972. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  973. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  974. e->getCommon());
  975. }
  976. /// Build the opaque value mapping for an OpaqueValueExpr whose source
  977. /// expression is set to the expression the OVE represents.
  978. OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
  979. : CGF(CGF) {
  980. if (OV) {
  981. assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
  982. "for OVE with no source expression");
  983. Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
  984. }
  985. }
  986. OpaqueValueMapping(CodeGenFunction &CGF,
  987. const OpaqueValueExpr *opaqueValue,
  988. LValue lvalue)
  989. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  990. }
  991. OpaqueValueMapping(CodeGenFunction &CGF,
  992. const OpaqueValueExpr *opaqueValue,
  993. RValue rvalue)
  994. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  995. }
  996. void pop() {
  997. Data.unbind(CGF);
  998. Data.clear();
  999. }
  1000. ~OpaqueValueMapping() {
  1001. if (Data.isValid()) Data.unbind(CGF);
  1002. }
  1003. };
  1004. private:
  1005. CGDebugInfo *DebugInfo;
  1006. bool DisableDebugInfo = false;
  1007. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  1008. /// calling llvm.stacksave for multiple VLAs in the same scope.
  1009. bool DidCallStackSave = false;
  1010. /// IndirectBranch - The first time an indirect goto is seen we create a block
  1011. /// with an indirect branch. Every time we see the address of a label taken,
  1012. /// we add the label to the indirect goto. Every subsequent indirect goto is
  1013. /// codegen'd as a jump to the IndirectBranch's basic block.
  1014. llvm::IndirectBrInst *IndirectBranch = nullptr;
  1015. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  1016. /// decls.
  1017. DeclMapTy LocalDeclMap;
  1018. // Keep track of the cleanups for callee-destructed parameters pushed to the
  1019. // cleanup stack so that they can be deactivated later.
  1020. llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
  1021. CalleeDestructedParamCleanups;
  1022. /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
  1023. /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
  1024. /// parameter.
  1025. llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
  1026. SizeArguments;
  1027. /// Track escaped local variables with auto storage. Used during SEH
  1028. /// outlining to produce a call to llvm.localescape.
  1029. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  1030. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  1031. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  1032. // BreakContinueStack - This keeps track of where break and continue
  1033. // statements should jump to.
  1034. struct BreakContinue {
  1035. BreakContinue(JumpDest Break, JumpDest Continue)
  1036. : BreakBlock(Break), ContinueBlock(Continue) {}
  1037. JumpDest BreakBlock;
  1038. JumpDest ContinueBlock;
  1039. };
  1040. SmallVector<BreakContinue, 8> BreakContinueStack;
  1041. /// Handles cancellation exit points in OpenMP-related constructs.
  1042. class OpenMPCancelExitStack {
  1043. /// Tracks cancellation exit point and join point for cancel-related exit
  1044. /// and normal exit.
  1045. struct CancelExit {
  1046. CancelExit() = default;
  1047. CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
  1048. JumpDest ContBlock)
  1049. : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
  1050. OpenMPDirectiveKind Kind = OMPD_unknown;
  1051. /// true if the exit block has been emitted already by the special
  1052. /// emitExit() call, false if the default codegen is used.
  1053. bool HasBeenEmitted = false;
  1054. JumpDest ExitBlock;
  1055. JumpDest ContBlock;
  1056. };
  1057. SmallVector<CancelExit, 8> Stack;
  1058. public:
  1059. OpenMPCancelExitStack() : Stack(1) {}
  1060. ~OpenMPCancelExitStack() = default;
  1061. /// Fetches the exit block for the current OpenMP construct.
  1062. JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
  1063. /// Emits exit block with special codegen procedure specific for the related
  1064. /// OpenMP construct + emits code for normal construct cleanup.
  1065. void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  1066. const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
  1067. if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
  1068. assert(CGF.getOMPCancelDestination(Kind).isValid());
  1069. assert(CGF.HaveInsertPoint());
  1070. assert(!Stack.back().HasBeenEmitted);
  1071. auto IP = CGF.Builder.saveAndClearIP();
  1072. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1073. CodeGen(CGF);
  1074. CGF.EmitBranch(Stack.back().ContBlock.getBlock());
  1075. CGF.Builder.restoreIP(IP);
  1076. Stack.back().HasBeenEmitted = true;
  1077. }
  1078. CodeGen(CGF);
  1079. }
  1080. /// Enter the cancel supporting \a Kind construct.
  1081. /// \param Kind OpenMP directive that supports cancel constructs.
  1082. /// \param HasCancel true, if the construct has inner cancel directive,
  1083. /// false otherwise.
  1084. void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
  1085. Stack.push_back({Kind,
  1086. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
  1087. : JumpDest(),
  1088. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
  1089. : JumpDest()});
  1090. }
  1091. /// Emits default exit point for the cancel construct (if the special one
  1092. /// has not be used) + join point for cancel/normal exits.
  1093. void exit(CodeGenFunction &CGF) {
  1094. if (getExitBlock().isValid()) {
  1095. assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
  1096. bool HaveIP = CGF.HaveInsertPoint();
  1097. if (!Stack.back().HasBeenEmitted) {
  1098. if (HaveIP)
  1099. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1100. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  1101. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  1102. }
  1103. CGF.EmitBlock(Stack.back().ContBlock.getBlock());
  1104. if (!HaveIP) {
  1105. CGF.Builder.CreateUnreachable();
  1106. CGF.Builder.ClearInsertionPoint();
  1107. }
  1108. }
  1109. Stack.pop_back();
  1110. }
  1111. };
  1112. OpenMPCancelExitStack OMPCancelStack;
  1113. CodeGenPGO PGO;
  1114. /// Calculate branch weights appropriate for PGO data
  1115. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  1116. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  1117. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  1118. uint64_t LoopCount);
  1119. public:
  1120. /// Increment the profiler's counter for the given statement by \p StepV.
  1121. /// If \p StepV is null, the default increment is 1.
  1122. void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
  1123. if (CGM.getCodeGenOpts().hasProfileClangInstr())
  1124. PGO.emitCounterIncrement(Builder, S, StepV);
  1125. PGO.setCurrentStmt(S);
  1126. }
  1127. /// Get the profiler's count for the given statement.
  1128. uint64_t getProfileCount(const Stmt *S) {
  1129. Optional<uint64_t> Count = PGO.getStmtCount(S);
  1130. if (!Count.hasValue())
  1131. return 0;
  1132. return *Count;
  1133. }
  1134. /// Set the profiler's current count.
  1135. void setCurrentProfileCount(uint64_t Count) {
  1136. PGO.setCurrentRegionCount(Count);
  1137. }
  1138. /// Get the profiler's current count. This is generally the count for the most
  1139. /// recently incremented counter.
  1140. uint64_t getCurrentProfileCount() {
  1141. return PGO.getCurrentRegionCount();
  1142. }
  1143. private:
  1144. /// SwitchInsn - This is nearest current switch instruction. It is null if
  1145. /// current context is not in a switch.
  1146. llvm::SwitchInst *SwitchInsn = nullptr;
  1147. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  1148. SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
  1149. /// CaseRangeBlock - This block holds if condition check for last case
  1150. /// statement range in current switch instruction.
  1151. llvm::BasicBlock *CaseRangeBlock = nullptr;
  1152. /// OpaqueLValues - Keeps track of the current set of opaque value
  1153. /// expressions.
  1154. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  1155. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  1156. // VLASizeMap - This keeps track of the associated size for each VLA type.
  1157. // We track this by the size expression rather than the type itself because
  1158. // in certain situations, like a const qualifier applied to an VLA typedef,
  1159. // multiple VLA types can share the same size expression.
  1160. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  1161. // enter/leave scopes.
  1162. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  1163. /// A block containing a single 'unreachable' instruction. Created
  1164. /// lazily by getUnreachableBlock().
  1165. llvm::BasicBlock *UnreachableBlock = nullptr;
  1166. /// Counts of the number return expressions in the function.
  1167. unsigned NumReturnExprs = 0;
  1168. /// Count the number of simple (constant) return expressions in the function.
  1169. unsigned NumSimpleReturnExprs = 0;
  1170. /// The last regular (non-return) debug location (breakpoint) in the function.
  1171. SourceLocation LastStopPoint;
  1172. public:
  1173. /// A scope within which we are constructing the fields of an object which
  1174. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  1175. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  1176. class FieldConstructionScope {
  1177. public:
  1178. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  1179. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  1180. CGF.CXXDefaultInitExprThis = This;
  1181. }
  1182. ~FieldConstructionScope() {
  1183. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  1184. }
  1185. private:
  1186. CodeGenFunction &CGF;
  1187. Address OldCXXDefaultInitExprThis;
  1188. };
  1189. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  1190. /// is overridden to be the object under construction.
  1191. class CXXDefaultInitExprScope {
  1192. public:
  1193. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  1194. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  1195. OldCXXThisAlignment(CGF.CXXThisAlignment) {
  1196. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  1197. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  1198. }
  1199. ~CXXDefaultInitExprScope() {
  1200. CGF.CXXThisValue = OldCXXThisValue;
  1201. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1202. }
  1203. public:
  1204. CodeGenFunction &CGF;
  1205. llvm::Value *OldCXXThisValue;
  1206. CharUnits OldCXXThisAlignment;
  1207. };
  1208. /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
  1209. /// current loop index is overridden.
  1210. class ArrayInitLoopExprScope {
  1211. public:
  1212. ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
  1213. : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
  1214. CGF.ArrayInitIndex = Index;
  1215. }
  1216. ~ArrayInitLoopExprScope() {
  1217. CGF.ArrayInitIndex = OldArrayInitIndex;
  1218. }
  1219. private:
  1220. CodeGenFunction &CGF;
  1221. llvm::Value *OldArrayInitIndex;
  1222. };
  1223. class InlinedInheritingConstructorScope {
  1224. public:
  1225. InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
  1226. : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
  1227. OldCurCodeDecl(CGF.CurCodeDecl),
  1228. OldCXXABIThisDecl(CGF.CXXABIThisDecl),
  1229. OldCXXABIThisValue(CGF.CXXABIThisValue),
  1230. OldCXXThisValue(CGF.CXXThisValue),
  1231. OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
  1232. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1233. OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
  1234. OldCXXInheritedCtorInitExprArgs(
  1235. std::move(CGF.CXXInheritedCtorInitExprArgs)) {
  1236. CGF.CurGD = GD;
  1237. CGF.CurFuncDecl = CGF.CurCodeDecl =
  1238. cast<CXXConstructorDecl>(GD.getDecl());
  1239. CGF.CXXABIThisDecl = nullptr;
  1240. CGF.CXXABIThisValue = nullptr;
  1241. CGF.CXXThisValue = nullptr;
  1242. CGF.CXXABIThisAlignment = CharUnits();
  1243. CGF.CXXThisAlignment = CharUnits();
  1244. CGF.ReturnValue = Address::invalid();
  1245. CGF.FnRetTy = QualType();
  1246. CGF.CXXInheritedCtorInitExprArgs.clear();
  1247. }
  1248. ~InlinedInheritingConstructorScope() {
  1249. CGF.CurGD = OldCurGD;
  1250. CGF.CurFuncDecl = OldCurFuncDecl;
  1251. CGF.CurCodeDecl = OldCurCodeDecl;
  1252. CGF.CXXABIThisDecl = OldCXXABIThisDecl;
  1253. CGF.CXXABIThisValue = OldCXXABIThisValue;
  1254. CGF.CXXThisValue = OldCXXThisValue;
  1255. CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
  1256. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1257. CGF.ReturnValue = OldReturnValue;
  1258. CGF.FnRetTy = OldFnRetTy;
  1259. CGF.CXXInheritedCtorInitExprArgs =
  1260. std::move(OldCXXInheritedCtorInitExprArgs);
  1261. }
  1262. private:
  1263. CodeGenFunction &CGF;
  1264. GlobalDecl OldCurGD;
  1265. const Decl *OldCurFuncDecl;
  1266. const Decl *OldCurCodeDecl;
  1267. ImplicitParamDecl *OldCXXABIThisDecl;
  1268. llvm::Value *OldCXXABIThisValue;
  1269. llvm::Value *OldCXXThisValue;
  1270. CharUnits OldCXXABIThisAlignment;
  1271. CharUnits OldCXXThisAlignment;
  1272. Address OldReturnValue;
  1273. QualType OldFnRetTy;
  1274. CallArgList OldCXXInheritedCtorInitExprArgs;
  1275. };
  1276. private:
  1277. /// CXXThisDecl - When generating code for a C++ member function,
  1278. /// this will hold the implicit 'this' declaration.
  1279. ImplicitParamDecl *CXXABIThisDecl = nullptr;
  1280. llvm::Value *CXXABIThisValue = nullptr;
  1281. llvm::Value *CXXThisValue = nullptr;
  1282. CharUnits CXXABIThisAlignment;
  1283. CharUnits CXXThisAlignment;
  1284. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  1285. /// this expression.
  1286. Address CXXDefaultInitExprThis = Address::invalid();
  1287. /// The current array initialization index when evaluating an
  1288. /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
  1289. llvm::Value *ArrayInitIndex = nullptr;
  1290. /// The values of function arguments to use when evaluating
  1291. /// CXXInheritedCtorInitExprs within this context.
  1292. CallArgList CXXInheritedCtorInitExprArgs;
  1293. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  1294. /// destructor, this will hold the implicit argument (e.g. VTT).
  1295. ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
  1296. llvm::Value *CXXStructorImplicitParamValue = nullptr;
  1297. /// OutermostConditional - Points to the outermost active
  1298. /// conditional control. This is used so that we know if a
  1299. /// temporary should be destroyed conditionally.
  1300. ConditionalEvaluation *OutermostConditional = nullptr;
  1301. /// The current lexical scope.
  1302. LexicalScope *CurLexicalScope = nullptr;
  1303. /// The current source location that should be used for exception
  1304. /// handling code.
  1305. SourceLocation CurEHLocation;
  1306. /// BlockByrefInfos - For each __block variable, contains
  1307. /// information about the layout of the variable.
  1308. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  1309. /// Used by -fsanitize=nullability-return to determine whether the return
  1310. /// value can be checked.
  1311. llvm::Value *RetValNullabilityPrecondition = nullptr;
  1312. /// Check if -fsanitize=nullability-return instrumentation is required for
  1313. /// this function.
  1314. bool requiresReturnValueNullabilityCheck() const {
  1315. return RetValNullabilityPrecondition;
  1316. }
  1317. /// Used to store precise source locations for return statements by the
  1318. /// runtime return value checks.
  1319. Address ReturnLocation = Address::invalid();
  1320. /// Check if the return value of this function requires sanitization.
  1321. bool requiresReturnValueCheck() const {
  1322. return requiresReturnValueNullabilityCheck() ||
  1323. (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  1324. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
  1325. }
  1326. llvm::BasicBlock *TerminateLandingPad = nullptr;
  1327. llvm::BasicBlock *TerminateHandler = nullptr;
  1328. llvm::BasicBlock *TrapBB = nullptr;
  1329. /// Terminate funclets keyed by parent funclet pad.
  1330. llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
  1331. /// Largest vector width used in ths function. Will be used to create a
  1332. /// function attribute.
  1333. unsigned LargestVectorWidth = 0;
  1334. /// True if we need emit the life-time markers.
  1335. const bool ShouldEmitLifetimeMarkers;
  1336. /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
  1337. /// the function metadata.
  1338. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  1339. llvm::Function *Fn);
  1340. public:
  1341. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  1342. ~CodeGenFunction();
  1343. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  1344. ASTContext &getContext() const { return CGM.getContext(); }
  1345. CGDebugInfo *getDebugInfo() {
  1346. if (DisableDebugInfo)
  1347. return nullptr;
  1348. return DebugInfo;
  1349. }
  1350. void disableDebugInfo() { DisableDebugInfo = true; }
  1351. void enableDebugInfo() { DisableDebugInfo = false; }
  1352. bool shouldUseFusedARCCalls() {
  1353. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1354. }
  1355. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1356. /// Returns a pointer to the function's exception object and selector slot,
  1357. /// which is assigned in every landing pad.
  1358. Address getExceptionSlot();
  1359. Address getEHSelectorSlot();
  1360. /// Returns the contents of the function's exception object and selector
  1361. /// slots.
  1362. llvm::Value *getExceptionFromSlot();
  1363. llvm::Value *getSelectorFromSlot();
  1364. Address getNormalCleanupDestSlot();
  1365. llvm::BasicBlock *getUnreachableBlock() {
  1366. if (!UnreachableBlock) {
  1367. UnreachableBlock = createBasicBlock("unreachable");
  1368. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1369. }
  1370. return UnreachableBlock;
  1371. }
  1372. llvm::BasicBlock *getInvokeDest() {
  1373. if (!EHStack.requiresLandingPad()) return nullptr;
  1374. return getInvokeDestImpl();
  1375. }
  1376. bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
  1377. const TargetInfo &getTarget() const { return Target; }
  1378. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1379. const TargetCodeGenInfo &getTargetHooks() const {
  1380. return CGM.getTargetCodeGenInfo();
  1381. }
  1382. //===--------------------------------------------------------------------===//
  1383. // Cleanups
  1384. //===--------------------------------------------------------------------===//
  1385. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  1386. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1387. Address arrayEndPointer,
  1388. QualType elementType,
  1389. CharUnits elementAlignment,
  1390. Destroyer *destroyer);
  1391. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1392. llvm::Value *arrayEnd,
  1393. QualType elementType,
  1394. CharUnits elementAlignment,
  1395. Destroyer *destroyer);
  1396. void pushDestroy(QualType::DestructionKind dtorKind,
  1397. Address addr, QualType type);
  1398. void pushEHDestroy(QualType::DestructionKind dtorKind,
  1399. Address addr, QualType type);
  1400. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  1401. Destroyer *destroyer, bool useEHCleanupForArray);
  1402. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  1403. QualType type, Destroyer *destroyer,
  1404. bool useEHCleanupForArray);
  1405. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  1406. llvm::Value *CompletePtr,
  1407. QualType ElementType);
  1408. void pushStackRestore(CleanupKind kind, Address SPMem);
  1409. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  1410. bool useEHCleanupForArray);
  1411. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  1412. Destroyer *destroyer,
  1413. bool useEHCleanupForArray,
  1414. const VarDecl *VD);
  1415. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1416. QualType elementType, CharUnits elementAlign,
  1417. Destroyer *destroyer,
  1418. bool checkZeroLength, bool useEHCleanup);
  1419. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1420. /// Determines whether an EH cleanup is required to destroy a type
  1421. /// with the given destruction kind.
  1422. bool needsEHCleanup(QualType::DestructionKind kind) {
  1423. switch (kind) {
  1424. case QualType::DK_none:
  1425. return false;
  1426. case QualType::DK_cxx_destructor:
  1427. case QualType::DK_objc_weak_lifetime:
  1428. case QualType::DK_nontrivial_c_struct:
  1429. return getLangOpts().Exceptions;
  1430. case QualType::DK_objc_strong_lifetime:
  1431. return getLangOpts().Exceptions &&
  1432. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1433. }
  1434. llvm_unreachable("bad destruction kind");
  1435. }
  1436. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1437. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1438. }
  1439. //===--------------------------------------------------------------------===//
  1440. // Objective-C
  1441. //===--------------------------------------------------------------------===//
  1442. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1443. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1444. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1445. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1446. const ObjCPropertyImplDecl *PID);
  1447. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1448. const ObjCPropertyImplDecl *propImpl,
  1449. const ObjCMethodDecl *GetterMothodDecl,
  1450. llvm::Constant *AtomicHelperFn);
  1451. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1452. ObjCMethodDecl *MD, bool ctor);
  1453. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1454. /// for the given property.
  1455. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1456. const ObjCPropertyImplDecl *PID);
  1457. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1458. const ObjCPropertyImplDecl *propImpl,
  1459. llvm::Constant *AtomicHelperFn);
  1460. //===--------------------------------------------------------------------===//
  1461. // Block Bits
  1462. //===--------------------------------------------------------------------===//
  1463. /// Emit block literal.
  1464. /// \return an LLVM value which is a pointer to a struct which contains
  1465. /// information about the block, including the block invoke function, the
  1466. /// captured variables, etc.
  1467. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1468. static void destroyBlockInfos(CGBlockInfo *info);
  1469. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1470. const CGBlockInfo &Info,
  1471. const DeclMapTy &ldm,
  1472. bool IsLambdaConversionToBlock,
  1473. bool BuildGlobalBlock);
  1474. /// Check if \p T is a C++ class that has a destructor that can throw.
  1475. static bool cxxDestructorCanThrow(QualType T);
  1476. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1477. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1478. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1479. const ObjCPropertyImplDecl *PID);
  1480. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1481. const ObjCPropertyImplDecl *PID);
  1482. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1483. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
  1484. bool CanThrow);
  1485. class AutoVarEmission;
  1486. void emitByrefStructureInit(const AutoVarEmission &emission);
  1487. /// Enter a cleanup to destroy a __block variable. Note that this
  1488. /// cleanup should be a no-op if the variable hasn't left the stack
  1489. /// yet; if a cleanup is required for the variable itself, that needs
  1490. /// to be done externally.
  1491. ///
  1492. /// \param Kind Cleanup kind.
  1493. ///
  1494. /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
  1495. /// structure that will be passed to _Block_object_dispose. When
  1496. /// \p LoadBlockVarAddr is true, the address of the field of the block
  1497. /// structure that holds the address of the __block structure.
  1498. ///
  1499. /// \param Flags The flag that will be passed to _Block_object_dispose.
  1500. ///
  1501. /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
  1502. /// \p Addr to get the address of the __block structure.
  1503. void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
  1504. bool LoadBlockVarAddr, bool CanThrow);
  1505. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1506. llvm::Value *ptr);
  1507. Address LoadBlockStruct();
  1508. Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1509. /// BuildBlockByrefAddress - Computes the location of the
  1510. /// data in a variable which is declared as __block.
  1511. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1512. bool followForward = true);
  1513. Address emitBlockByrefAddress(Address baseAddr,
  1514. const BlockByrefInfo &info,
  1515. bool followForward,
  1516. const llvm::Twine &name);
  1517. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1518. QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
  1519. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1520. const CGFunctionInfo &FnInfo);
  1521. /// Annotate the function with an attribute that disables TSan checking at
  1522. /// runtime.
  1523. void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
  1524. /// Emit code for the start of a function.
  1525. /// \param Loc The location to be associated with the function.
  1526. /// \param StartLoc The location of the function body.
  1527. void StartFunction(GlobalDecl GD,
  1528. QualType RetTy,
  1529. llvm::Function *Fn,
  1530. const CGFunctionInfo &FnInfo,
  1531. const FunctionArgList &Args,
  1532. SourceLocation Loc = SourceLocation(),
  1533. SourceLocation StartLoc = SourceLocation());
  1534. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
  1535. void EmitConstructorBody(FunctionArgList &Args);
  1536. void EmitDestructorBody(FunctionArgList &Args);
  1537. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1538. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1539. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1540. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1541. CallArgList &CallArgs);
  1542. void EmitLambdaBlockInvokeBody();
  1543. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1544. void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
  1545. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1546. /// Emit the unified return block, trying to avoid its emission when
  1547. /// possible.
  1548. /// \return The debug location of the user written return statement if the
  1549. /// return block is is avoided.
  1550. llvm::DebugLoc EmitReturnBlock();
  1551. /// FinishFunction - Complete IR generation of the current function. It is
  1552. /// legal to call this function even if there is no current insertion point.
  1553. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1554. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1555. const CGFunctionInfo &FnInfo, bool IsUnprototyped);
  1556. void EmitCallAndReturnForThunk(llvm::Constant *Callee, const ThunkInfo *Thunk,
  1557. bool IsUnprototyped);
  1558. void FinishThunk();
  1559. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1560. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1561. llvm::Value *Callee);
  1562. /// Generate a thunk for the given method.
  1563. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1564. GlobalDecl GD, const ThunkInfo &Thunk,
  1565. bool IsUnprototyped);
  1566. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1567. const CGFunctionInfo &FnInfo,
  1568. GlobalDecl GD, const ThunkInfo &Thunk);
  1569. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1570. FunctionArgList &Args);
  1571. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
  1572. /// Struct with all information about dynamic [sub]class needed to set vptr.
  1573. struct VPtr {
  1574. BaseSubobject Base;
  1575. const CXXRecordDecl *NearestVBase;
  1576. CharUnits OffsetFromNearestVBase;
  1577. const CXXRecordDecl *VTableClass;
  1578. };
  1579. /// Initialize the vtable pointer of the given subobject.
  1580. void InitializeVTablePointer(const VPtr &vptr);
  1581. typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
  1582. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1583. VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
  1584. void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
  1585. CharUnits OffsetFromNearestVBase,
  1586. bool BaseIsNonVirtualPrimaryBase,
  1587. const CXXRecordDecl *VTableClass,
  1588. VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
  1589. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1590. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1591. /// to by This.
  1592. llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
  1593. const CXXRecordDecl *VTableClass);
  1594. enum CFITypeCheckKind {
  1595. CFITCK_VCall,
  1596. CFITCK_NVCall,
  1597. CFITCK_DerivedCast,
  1598. CFITCK_UnrelatedCast,
  1599. CFITCK_ICall,
  1600. CFITCK_NVMFCall,
  1601. CFITCK_VMFCall,
  1602. };
  1603. /// Derived is the presumed address of an object of type T after a
  1604. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1605. /// table for Derived belongs to a class derived from T.
  1606. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1607. bool MayBeNull, CFITypeCheckKind TCK,
  1608. SourceLocation Loc);
  1609. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1610. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1611. void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
  1612. CFITypeCheckKind TCK, SourceLocation Loc);
  1613. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1614. /// RD using llvm.type.test.
  1615. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1616. CFITypeCheckKind TCK, SourceLocation Loc);
  1617. /// If whole-program virtual table optimization is enabled, emit an assumption
  1618. /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
  1619. /// enabled, emit a check that VTable is a member of RD's type identifier.
  1620. void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  1621. llvm::Value *VTable, SourceLocation Loc);
  1622. /// Returns whether we should perform a type checked load when loading a
  1623. /// virtual function for virtual calls to members of RD. This is generally
  1624. /// true when both vcall CFI and whole-program-vtables are enabled.
  1625. bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
  1626. /// Emit a type checked load from the given vtable.
  1627. llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
  1628. uint64_t VTableByteOffset);
  1629. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1630. /// given phase of destruction for a destructor. The end result
  1631. /// should call destructors on members and base classes in reverse
  1632. /// order of their construction.
  1633. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1634. /// ShouldInstrumentFunction - Return true if the current function should be
  1635. /// instrumented with __cyg_profile_func_* calls
  1636. bool ShouldInstrumentFunction();
  1637. /// ShouldXRayInstrument - Return true if the current function should be
  1638. /// instrumented with XRay nop sleds.
  1639. bool ShouldXRayInstrumentFunction() const;
  1640. /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
  1641. /// XRay custom event handling calls.
  1642. bool AlwaysEmitXRayCustomEvents() const;
  1643. /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
  1644. /// XRay typed event handling calls.
  1645. bool AlwaysEmitXRayTypedEvents() const;
  1646. /// Encode an address into a form suitable for use in a function prologue.
  1647. llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
  1648. llvm::Constant *Addr);
  1649. /// Decode an address used in a function prologue, encoded by \c
  1650. /// EncodeAddrForUseInPrologue.
  1651. llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
  1652. llvm::Value *EncodedAddr);
  1653. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1654. /// arguments for the given function. This is also responsible for naming the
  1655. /// LLVM function arguments.
  1656. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1657. llvm::Function *Fn,
  1658. const FunctionArgList &Args);
  1659. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1660. /// given temporary.
  1661. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1662. SourceLocation EndLoc);
  1663. /// Emit a test that checks if the return value \p RV is nonnull.
  1664. void EmitReturnValueCheck(llvm::Value *RV);
  1665. /// EmitStartEHSpec - Emit the start of the exception spec.
  1666. void EmitStartEHSpec(const Decl *D);
  1667. /// EmitEndEHSpec - Emit the end of the exception spec.
  1668. void EmitEndEHSpec(const Decl *D);
  1669. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1670. llvm::BasicBlock *getTerminateLandingPad();
  1671. /// getTerminateLandingPad - Return a cleanup funclet that just calls
  1672. /// terminate.
  1673. llvm::BasicBlock *getTerminateFunclet();
  1674. /// getTerminateHandler - Return a handler (not a landing pad, just
  1675. /// a catch handler) that just calls terminate. This is used when
  1676. /// a terminate scope encloses a try.
  1677. llvm::BasicBlock *getTerminateHandler();
  1678. llvm::Type *ConvertTypeForMem(QualType T);
  1679. llvm::Type *ConvertType(QualType T);
  1680. llvm::Type *ConvertType(const TypeDecl *T) {
  1681. return ConvertType(getContext().getTypeDeclType(T));
  1682. }
  1683. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1684. /// generating code for an Objective-C method.
  1685. llvm::Value *LoadObjCSelf();
  1686. /// TypeOfSelfObject - Return type of object that this self represents.
  1687. QualType TypeOfSelfObject();
  1688. /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
  1689. static TypeEvaluationKind getEvaluationKind(QualType T);
  1690. static bool hasScalarEvaluationKind(QualType T) {
  1691. return getEvaluationKind(T) == TEK_Scalar;
  1692. }
  1693. static bool hasAggregateEvaluationKind(QualType T) {
  1694. return getEvaluationKind(T) == TEK_Aggregate;
  1695. }
  1696. /// createBasicBlock - Create an LLVM basic block.
  1697. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1698. llvm::Function *parent = nullptr,
  1699. llvm::BasicBlock *before = nullptr) {
  1700. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1701. }
  1702. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1703. /// label maps to.
  1704. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1705. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1706. /// another basic block, simplify it. This assumes that no other code could
  1707. /// potentially reference the basic block.
  1708. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1709. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1710. /// adding a fall-through branch from the current insert block if
  1711. /// necessary. It is legal to call this function even if there is no current
  1712. /// insertion point.
  1713. ///
  1714. /// IsFinished - If true, indicates that the caller has finished emitting
  1715. /// branches to the given block and does not expect to emit code into it. This
  1716. /// means the block can be ignored if it is unreachable.
  1717. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1718. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1719. /// near its uses, and leave the insertion point in it.
  1720. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1721. /// EmitBranch - Emit a branch to the specified basic block from the current
  1722. /// insert block, taking care to avoid creation of branches from dummy
  1723. /// blocks. It is legal to call this function even if there is no current
  1724. /// insertion point.
  1725. ///
  1726. /// This function clears the current insertion point. The caller should follow
  1727. /// calls to this function with calls to Emit*Block prior to generation new
  1728. /// code.
  1729. void EmitBranch(llvm::BasicBlock *Block);
  1730. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1731. /// indicates that the current code being emitted is unreachable.
  1732. bool HaveInsertPoint() const {
  1733. return Builder.GetInsertBlock() != nullptr;
  1734. }
  1735. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1736. /// emitted IR has a place to go. Note that by definition, if this function
  1737. /// creates a block then that block is unreachable; callers may do better to
  1738. /// detect when no insertion point is defined and simply skip IR generation.
  1739. void EnsureInsertPoint() {
  1740. if (!HaveInsertPoint())
  1741. EmitBlock(createBasicBlock());
  1742. }
  1743. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1744. /// specified stmt yet.
  1745. void ErrorUnsupported(const Stmt *S, const char *Type);
  1746. //===--------------------------------------------------------------------===//
  1747. // Helpers
  1748. //===--------------------------------------------------------------------===//
  1749. LValue MakeAddrLValue(Address Addr, QualType T,
  1750. AlignmentSource Source = AlignmentSource::Type) {
  1751. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  1752. CGM.getTBAAAccessInfo(T));
  1753. }
  1754. LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
  1755. TBAAAccessInfo TBAAInfo) {
  1756. return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
  1757. }
  1758. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1759. AlignmentSource Source = AlignmentSource::Type) {
  1760. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1761. LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
  1762. }
  1763. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1764. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
  1765. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1766. BaseInfo, TBAAInfo);
  1767. }
  1768. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  1769. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1770. CharUnits getNaturalTypeAlignment(QualType T,
  1771. LValueBaseInfo *BaseInfo = nullptr,
  1772. TBAAAccessInfo *TBAAInfo = nullptr,
  1773. bool forPointeeType = false);
  1774. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1775. LValueBaseInfo *BaseInfo = nullptr,
  1776. TBAAAccessInfo *TBAAInfo = nullptr);
  1777. Address EmitLoadOfReference(LValue RefLVal,
  1778. LValueBaseInfo *PointeeBaseInfo = nullptr,
  1779. TBAAAccessInfo *PointeeTBAAInfo = nullptr);
  1780. LValue EmitLoadOfReferenceLValue(LValue RefLVal);
  1781. LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
  1782. AlignmentSource Source =
  1783. AlignmentSource::Type) {
  1784. LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
  1785. CGM.getTBAAAccessInfo(RefTy));
  1786. return EmitLoadOfReferenceLValue(RefLVal);
  1787. }
  1788. Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
  1789. LValueBaseInfo *BaseInfo = nullptr,
  1790. TBAAAccessInfo *TBAAInfo = nullptr);
  1791. LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
  1792. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  1793. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  1794. /// insertion point of the builder. The caller is responsible for setting an
  1795. /// appropriate alignment on
  1796. /// the alloca.
  1797. ///
  1798. /// \p ArraySize is the number of array elements to be allocated if it
  1799. /// is not nullptr.
  1800. ///
  1801. /// LangAS::Default is the address space of pointers to local variables and
  1802. /// temporaries, as exposed in the source language. In certain
  1803. /// configurations, this is not the same as the alloca address space, and a
  1804. /// cast is needed to lift the pointer from the alloca AS into
  1805. /// LangAS::Default. This can happen when the target uses a restricted
  1806. /// address space for the stack but the source language requires
  1807. /// LangAS::Default to be a generic address space. The latter condition is
  1808. /// common for most programming languages; OpenCL is an exception in that
  1809. /// LangAS::Default is the private address space, which naturally maps
  1810. /// to the stack.
  1811. ///
  1812. /// Because the address of a temporary is often exposed to the program in
  1813. /// various ways, this function will perform the cast. The original alloca
  1814. /// instruction is returned through \p Alloca if it is not nullptr.
  1815. ///
  1816. /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
  1817. /// more efficient if the caller knows that the address will not be exposed.
  1818. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
  1819. llvm::Value *ArraySize = nullptr);
  1820. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  1821. const Twine &Name = "tmp",
  1822. llvm::Value *ArraySize = nullptr,
  1823. Address *Alloca = nullptr);
  1824. Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
  1825. const Twine &Name = "tmp",
  1826. llvm::Value *ArraySize = nullptr);
  1827. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  1828. /// default ABI alignment of the given LLVM type.
  1829. ///
  1830. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  1831. /// any given AST type that happens to have been lowered to the
  1832. /// given IR type. This should only ever be used for function-local,
  1833. /// IR-driven manipulations like saving and restoring a value. Do
  1834. /// not hand this address off to arbitrary IRGen routines, and especially
  1835. /// do not pass it as an argument to a function that might expect a
  1836. /// properly ABI-aligned value.
  1837. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  1838. const Twine &Name = "tmp");
  1839. /// InitTempAlloca - Provide an initial value for the given alloca which
  1840. /// will be observable at all locations in the function.
  1841. ///
  1842. /// The address should be something that was returned from one of
  1843. /// the CreateTempAlloca or CreateMemTemp routines, and the
  1844. /// initializer must be valid in the entry block (i.e. it must
  1845. /// either be a constant or an argument value).
  1846. void InitTempAlloca(Address Alloca, llvm::Value *Value);
  1847. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1848. /// appropriate alignment. This routine should only be used when an temporary
  1849. /// value needs to be stored into an alloca (for example, to avoid explicit
  1850. /// PHI construction), but the type is the IR type, not the type appropriate
  1851. /// for storing in memory.
  1852. ///
  1853. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  1854. /// ConvertType instead of ConvertTypeForMem.
  1855. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1856. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1857. /// appropriate alignmen and cast it to the default address space. Returns
  1858. /// the original alloca instruction by \p Alloca if it is not nullptr.
  1859. Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
  1860. Address *Alloca = nullptr);
  1861. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
  1862. Address *Alloca = nullptr);
  1863. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1864. /// appropriate alignmen without casting it to the default address space.
  1865. Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
  1866. Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
  1867. const Twine &Name = "tmp");
  1868. /// CreateAggTemp - Create a temporary memory object for the given
  1869. /// aggregate type.
  1870. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1871. return AggValueSlot::forAddr(CreateMemTemp(T, Name),
  1872. T.getQualifiers(),
  1873. AggValueSlot::IsNotDestructed,
  1874. AggValueSlot::DoesNotNeedGCBarriers,
  1875. AggValueSlot::IsNotAliased,
  1876. AggValueSlot::DoesNotOverlap);
  1877. }
  1878. /// Emit a cast to void* in the appropriate address space.
  1879. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1880. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1881. /// expression and compare the result against zero, returning an Int1Ty value.
  1882. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1883. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1884. void EmitIgnoredExpr(const Expr *E);
  1885. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1886. /// any type. The result is returned as an RValue struct. If this is an
  1887. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1888. /// the result should be returned.
  1889. ///
  1890. /// \param ignoreResult True if the resulting value isn't used.
  1891. RValue EmitAnyExpr(const Expr *E,
  1892. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1893. bool ignoreResult = false);
  1894. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1895. // or the value of the expression, depending on how va_list is defined.
  1896. Address EmitVAListRef(const Expr *E);
  1897. /// Emit a "reference" to a __builtin_ms_va_list; this is
  1898. /// always the value of the expression, because a __builtin_ms_va_list is a
  1899. /// pointer to a char.
  1900. Address EmitMSVAListRef(const Expr *E);
  1901. /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
  1902. /// always be accessible even if no aggregate location is provided.
  1903. RValue EmitAnyExprToTemp(const Expr *E);
  1904. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1905. /// arbitrary expression into the given memory location.
  1906. void EmitAnyExprToMem(const Expr *E, Address Location,
  1907. Qualifiers Quals, bool IsInitializer);
  1908. void EmitAnyExprToExn(const Expr *E, Address Addr);
  1909. /// EmitExprAsInit - Emits the code necessary to initialize a
  1910. /// location in memory with the given initializer.
  1911. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1912. bool capturedByInit);
  1913. /// hasVolatileMember - returns true if aggregate type has a volatile
  1914. /// member.
  1915. bool hasVolatileMember(QualType T) {
  1916. if (const RecordType *RT = T->getAs<RecordType>()) {
  1917. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1918. return RD->hasVolatileMember();
  1919. }
  1920. return false;
  1921. }
  1922. /// Determine whether a return value slot may overlap some other object.
  1923. AggValueSlot::Overlap_t overlapForReturnValue() {
  1924. // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
  1925. // class subobjects. These cases may need to be revisited depending on the
  1926. // resolution of the relevant core issue.
  1927. return AggValueSlot::DoesNotOverlap;
  1928. }
  1929. /// Determine whether a field initialization may overlap some other object.
  1930. AggValueSlot::Overlap_t overlapForFieldInit(const FieldDecl *FD) {
  1931. // FIXME: These cases can result in overlap as a result of P0840R0's
  1932. // [[no_unique_address]] attribute. We can still infer NoOverlap in the
  1933. // presence of that attribute if the field is within the nvsize of its
  1934. // containing class, because non-virtual subobjects are initialized in
  1935. // address order.
  1936. return AggValueSlot::DoesNotOverlap;
  1937. }
  1938. /// Determine whether a base class initialization may overlap some other
  1939. /// object.
  1940. AggValueSlot::Overlap_t overlapForBaseInit(const CXXRecordDecl *RD,
  1941. const CXXRecordDecl *BaseRD,
  1942. bool IsVirtual);
  1943. /// Emit an aggregate assignment.
  1944. void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
  1945. bool IsVolatile = hasVolatileMember(EltTy);
  1946. EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
  1947. }
  1948. void EmitAggregateCopyCtor(LValue Dest, LValue Src,
  1949. AggValueSlot::Overlap_t MayOverlap) {
  1950. EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
  1951. }
  1952. /// EmitAggregateCopy - Emit an aggregate copy.
  1953. ///
  1954. /// \param isVolatile \c true iff either the source or the destination is
  1955. /// volatile.
  1956. /// \param MayOverlap Whether the tail padding of the destination might be
  1957. /// occupied by some other object. More efficient code can often be
  1958. /// generated if not.
  1959. void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
  1960. AggValueSlot::Overlap_t MayOverlap,
  1961. bool isVolatile = false);
  1962. /// GetAddrOfLocalVar - Return the address of a local variable.
  1963. Address GetAddrOfLocalVar(const VarDecl *VD) {
  1964. auto it = LocalDeclMap.find(VD);
  1965. assert(it != LocalDeclMap.end() &&
  1966. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1967. return it->second;
  1968. }
  1969. /// Given an opaque value expression, return its LValue mapping if it exists,
  1970. /// otherwise create one.
  1971. LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
  1972. /// Given an opaque value expression, return its RValue mapping if it exists,
  1973. /// otherwise create one.
  1974. RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
  1975. /// Get the index of the current ArrayInitLoopExpr, if any.
  1976. llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
  1977. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1978. /// the input field number being accessed.
  1979. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1980. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1981. llvm::BasicBlock *GetIndirectGotoBlock();
  1982. /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
  1983. static bool IsWrappedCXXThis(const Expr *E);
  1984. /// EmitNullInitialization - Generate code to set a value of the given type to
  1985. /// null, If the type contains data member pointers, they will be initialized
  1986. /// to -1 in accordance with the Itanium C++ ABI.
  1987. void EmitNullInitialization(Address DestPtr, QualType Ty);
  1988. /// Emits a call to an LLVM variable-argument intrinsic, either
  1989. /// \c llvm.va_start or \c llvm.va_end.
  1990. /// \param ArgValue A reference to the \c va_list as emitted by either
  1991. /// \c EmitVAListRef or \c EmitMSVAListRef.
  1992. /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
  1993. /// calls \c llvm.va_end.
  1994. llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
  1995. /// Generate code to get an argument from the passed in pointer
  1996. /// and update it accordingly.
  1997. /// \param VE The \c VAArgExpr for which to generate code.
  1998. /// \param VAListAddr Receives a reference to the \c va_list as emitted by
  1999. /// either \c EmitVAListRef or \c EmitMSVAListRef.
  2000. /// \returns A pointer to the argument.
  2001. // FIXME: We should be able to get rid of this method and use the va_arg
  2002. // instruction in LLVM instead once it works well enough.
  2003. Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
  2004. /// emitArrayLength - Compute the length of an array, even if it's a
  2005. /// VLA, and drill down to the base element type.
  2006. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  2007. QualType &baseType,
  2008. Address &addr);
  2009. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  2010. /// the given variably-modified type and store them in the VLASizeMap.
  2011. ///
  2012. /// This function can be called with a null (unreachable) insert point.
  2013. void EmitVariablyModifiedType(QualType Ty);
  2014. struct VlaSizePair {
  2015. llvm::Value *NumElts;
  2016. QualType Type;
  2017. VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
  2018. };
  2019. /// Return the number of elements for a single dimension
  2020. /// for the given array type.
  2021. VlaSizePair getVLAElements1D(const VariableArrayType *vla);
  2022. VlaSizePair getVLAElements1D(QualType vla);
  2023. /// Returns an LLVM value that corresponds to the size,
  2024. /// in non-variably-sized elements, of a variable length array type,
  2025. /// plus that largest non-variably-sized element type. Assumes that
  2026. /// the type has already been emitted with EmitVariablyModifiedType.
  2027. VlaSizePair getVLASize(const VariableArrayType *vla);
  2028. VlaSizePair getVLASize(QualType vla);
  2029. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  2030. /// generating code for an C++ member function.
  2031. llvm::Value *LoadCXXThis() {
  2032. assert(CXXThisValue && "no 'this' value for this function");
  2033. return CXXThisValue;
  2034. }
  2035. Address LoadCXXThisAddress();
  2036. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  2037. /// virtual bases.
  2038. // FIXME: Every place that calls LoadCXXVTT is something
  2039. // that needs to be abstracted properly.
  2040. llvm::Value *LoadCXXVTT() {
  2041. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  2042. return CXXStructorImplicitParamValue;
  2043. }
  2044. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  2045. /// complete class to the given direct base.
  2046. Address
  2047. GetAddressOfDirectBaseInCompleteClass(Address Value,
  2048. const CXXRecordDecl *Derived,
  2049. const CXXRecordDecl *Base,
  2050. bool BaseIsVirtual);
  2051. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  2052. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  2053. /// load of 'this' and returns address of the base class.
  2054. Address GetAddressOfBaseClass(Address Value,
  2055. const CXXRecordDecl *Derived,
  2056. CastExpr::path_const_iterator PathBegin,
  2057. CastExpr::path_const_iterator PathEnd,
  2058. bool NullCheckValue, SourceLocation Loc);
  2059. Address GetAddressOfDerivedClass(Address Value,
  2060. const CXXRecordDecl *Derived,
  2061. CastExpr::path_const_iterator PathBegin,
  2062. CastExpr::path_const_iterator PathEnd,
  2063. bool NullCheckValue);
  2064. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  2065. /// base constructor/destructor with virtual bases.
  2066. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  2067. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  2068. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  2069. bool Delegating);
  2070. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2071. CXXCtorType CtorType,
  2072. const FunctionArgList &Args,
  2073. SourceLocation Loc);
  2074. // It's important not to confuse this and the previous function. Delegating
  2075. // constructors are the C++0x feature. The constructor delegate optimization
  2076. // is used to reduce duplication in the base and complete consturctors where
  2077. // they are substantially the same.
  2078. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2079. const FunctionArgList &Args);
  2080. /// Emit a call to an inheriting constructor (that is, one that invokes a
  2081. /// constructor inherited from a base class) by inlining its definition. This
  2082. /// is necessary if the ABI does not support forwarding the arguments to the
  2083. /// base class constructor (because they're variadic or similar).
  2084. void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2085. CXXCtorType CtorType,
  2086. bool ForVirtualBase,
  2087. bool Delegating,
  2088. CallArgList &Args);
  2089. /// Emit a call to a constructor inherited from a base class, passing the
  2090. /// current constructor's arguments along unmodified (without even making
  2091. /// a copy).
  2092. void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
  2093. bool ForVirtualBase, Address This,
  2094. bool InheritedFromVBase,
  2095. const CXXInheritedCtorInitExpr *E);
  2096. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2097. bool ForVirtualBase, bool Delegating,
  2098. Address This, const CXXConstructExpr *E,
  2099. AggValueSlot::Overlap_t Overlap,
  2100. bool NewPointerIsChecked);
  2101. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  2102. bool ForVirtualBase, bool Delegating,
  2103. Address This, CallArgList &Args,
  2104. AggValueSlot::Overlap_t Overlap,
  2105. SourceLocation Loc,
  2106. bool NewPointerIsChecked);
  2107. /// Emit assumption load for all bases. Requires to be be called only on
  2108. /// most-derived class and not under construction of the object.
  2109. void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
  2110. /// Emit assumption that vptr load == global vtable.
  2111. void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
  2112. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  2113. Address This, Address Src,
  2114. const CXXConstructExpr *E);
  2115. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2116. const ArrayType *ArrayTy,
  2117. Address ArrayPtr,
  2118. const CXXConstructExpr *E,
  2119. bool NewPointerIsChecked,
  2120. bool ZeroInitialization = false);
  2121. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  2122. llvm::Value *NumElements,
  2123. Address ArrayPtr,
  2124. const CXXConstructExpr *E,
  2125. bool NewPointerIsChecked,
  2126. bool ZeroInitialization = false);
  2127. static Destroyer destroyCXXObject;
  2128. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  2129. bool ForVirtualBase, bool Delegating,
  2130. Address This);
  2131. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  2132. llvm::Type *ElementTy, Address NewPtr,
  2133. llvm::Value *NumElements,
  2134. llvm::Value *AllocSizeWithoutCookie);
  2135. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  2136. Address Ptr);
  2137. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  2138. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  2139. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  2140. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  2141. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  2142. QualType DeleteTy, llvm::Value *NumElements = nullptr,
  2143. CharUnits CookieSize = CharUnits());
  2144. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  2145. const CallExpr *TheCallExpr, bool IsDelete);
  2146. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  2147. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  2148. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  2149. /// Situations in which we might emit a check for the suitability of a
  2150. /// pointer or glvalue.
  2151. enum TypeCheckKind {
  2152. /// Checking the operand of a load. Must be suitably sized and aligned.
  2153. TCK_Load,
  2154. /// Checking the destination of a store. Must be suitably sized and aligned.
  2155. TCK_Store,
  2156. /// Checking the bound value in a reference binding. Must be suitably sized
  2157. /// and aligned, but is not required to refer to an object (until the
  2158. /// reference is used), per core issue 453.
  2159. TCK_ReferenceBinding,
  2160. /// Checking the object expression in a non-static data member access. Must
  2161. /// be an object within its lifetime.
  2162. TCK_MemberAccess,
  2163. /// Checking the 'this' pointer for a call to a non-static member function.
  2164. /// Must be an object within its lifetime.
  2165. TCK_MemberCall,
  2166. /// Checking the 'this' pointer for a constructor call.
  2167. TCK_ConstructorCall,
  2168. /// Checking the operand of a static_cast to a derived pointer type. Must be
  2169. /// null or an object within its lifetime.
  2170. TCK_DowncastPointer,
  2171. /// Checking the operand of a static_cast to a derived reference type. Must
  2172. /// be an object within its lifetime.
  2173. TCK_DowncastReference,
  2174. /// Checking the operand of a cast to a base object. Must be suitably sized
  2175. /// and aligned.
  2176. TCK_Upcast,
  2177. /// Checking the operand of a cast to a virtual base object. Must be an
  2178. /// object within its lifetime.
  2179. TCK_UpcastToVirtualBase,
  2180. /// Checking the value assigned to a _Nonnull pointer. Must not be null.
  2181. TCK_NonnullAssign,
  2182. /// Checking the operand of a dynamic_cast or a typeid expression. Must be
  2183. /// null or an object within its lifetime.
  2184. TCK_DynamicOperation
  2185. };
  2186. /// Determine whether the pointer type check \p TCK permits null pointers.
  2187. static bool isNullPointerAllowed(TypeCheckKind TCK);
  2188. /// Determine whether the pointer type check \p TCK requires a vptr check.
  2189. static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
  2190. /// Whether any type-checking sanitizers are enabled. If \c false,
  2191. /// calls to EmitTypeCheck can be skipped.
  2192. bool sanitizePerformTypeCheck() const;
  2193. /// Emit a check that \p V is the address of storage of the
  2194. /// appropriate size and alignment for an object of type \p Type.
  2195. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  2196. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  2197. SanitizerSet SkippedChecks = SanitizerSet());
  2198. /// Emit a check that \p Base points into an array object, which
  2199. /// we can access at index \p Index. \p Accessed should be \c false if we
  2200. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  2201. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  2202. QualType IndexType, bool Accessed);
  2203. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2204. bool isInc, bool isPre);
  2205. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  2206. bool isInc, bool isPre);
  2207. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  2208. llvm::Value *OffsetValue = nullptr) {
  2209. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  2210. OffsetValue);
  2211. }
  2212. /// Converts Location to a DebugLoc, if debug information is enabled.
  2213. llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
  2214. //===--------------------------------------------------------------------===//
  2215. // Declaration Emission
  2216. //===--------------------------------------------------------------------===//
  2217. /// EmitDecl - Emit a declaration.
  2218. ///
  2219. /// This function can be called with a null (unreachable) insert point.
  2220. void EmitDecl(const Decl &D);
  2221. /// EmitVarDecl - Emit a local variable declaration.
  2222. ///
  2223. /// This function can be called with a null (unreachable) insert point.
  2224. void EmitVarDecl(const VarDecl &D);
  2225. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  2226. bool capturedByInit);
  2227. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  2228. llvm::Value *Address);
  2229. /// Determine whether the given initializer is trivial in the sense
  2230. /// that it requires no code to be generated.
  2231. bool isTrivialInitializer(const Expr *Init);
  2232. /// EmitAutoVarDecl - Emit an auto variable declaration.
  2233. ///
  2234. /// This function can be called with a null (unreachable) insert point.
  2235. void EmitAutoVarDecl(const VarDecl &D);
  2236. class AutoVarEmission {
  2237. friend class CodeGenFunction;
  2238. const VarDecl *Variable;
  2239. /// The address of the alloca for languages with explicit address space
  2240. /// (e.g. OpenCL) or alloca casted to generic pointer for address space
  2241. /// agnostic languages (e.g. C++). Invalid if the variable was emitted
  2242. /// as a global constant.
  2243. Address Addr;
  2244. llvm::Value *NRVOFlag;
  2245. /// True if the variable is a __block variable.
  2246. bool IsByRef;
  2247. /// True if the variable is of aggregate type and has a constant
  2248. /// initializer.
  2249. bool IsConstantAggregate;
  2250. /// Non-null if we should use lifetime annotations.
  2251. llvm::Value *SizeForLifetimeMarkers;
  2252. /// Address with original alloca instruction. Invalid if the variable was
  2253. /// emitted as a global constant.
  2254. Address AllocaAddr;
  2255. struct Invalid {};
  2256. AutoVarEmission(Invalid)
  2257. : Variable(nullptr), Addr(Address::invalid()),
  2258. AllocaAddr(Address::invalid()) {}
  2259. AutoVarEmission(const VarDecl &variable)
  2260. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  2261. IsByRef(false), IsConstantAggregate(false),
  2262. SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
  2263. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  2264. public:
  2265. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  2266. bool useLifetimeMarkers() const {
  2267. return SizeForLifetimeMarkers != nullptr;
  2268. }
  2269. llvm::Value *getSizeForLifetimeMarkers() const {
  2270. assert(useLifetimeMarkers());
  2271. return SizeForLifetimeMarkers;
  2272. }
  2273. /// Returns the raw, allocated address, which is not necessarily
  2274. /// the address of the object itself. It is casted to default
  2275. /// address space for address space agnostic languages.
  2276. Address getAllocatedAddress() const {
  2277. return Addr;
  2278. }
  2279. /// Returns the address for the original alloca instruction.
  2280. Address getOriginalAllocatedAddress() const { return AllocaAddr; }
  2281. /// Returns the address of the object within this declaration.
  2282. /// Note that this does not chase the forwarding pointer for
  2283. /// __block decls.
  2284. Address getObjectAddress(CodeGenFunction &CGF) const {
  2285. if (!IsByRef) return Addr;
  2286. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  2287. }
  2288. };
  2289. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  2290. void EmitAutoVarInit(const AutoVarEmission &emission);
  2291. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  2292. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  2293. QualType::DestructionKind dtorKind);
  2294. /// Emits the alloca and debug information for the size expressions for each
  2295. /// dimension of an array. It registers the association of its (1-dimensional)
  2296. /// QualTypes and size expression's debug node, so that CGDebugInfo can
  2297. /// reference this node when creating the DISubrange object to describe the
  2298. /// array types.
  2299. void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
  2300. const VarDecl &D,
  2301. bool EmitDebugInfo);
  2302. void EmitStaticVarDecl(const VarDecl &D,
  2303. llvm::GlobalValue::LinkageTypes Linkage);
  2304. class ParamValue {
  2305. llvm::Value *Value;
  2306. unsigned Alignment;
  2307. ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
  2308. public:
  2309. static ParamValue forDirect(llvm::Value *value) {
  2310. return ParamValue(value, 0);
  2311. }
  2312. static ParamValue forIndirect(Address addr) {
  2313. assert(!addr.getAlignment().isZero());
  2314. return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
  2315. }
  2316. bool isIndirect() const { return Alignment != 0; }
  2317. llvm::Value *getAnyValue() const { return Value; }
  2318. llvm::Value *getDirectValue() const {
  2319. assert(!isIndirect());
  2320. return Value;
  2321. }
  2322. Address getIndirectAddress() const {
  2323. assert(isIndirect());
  2324. return Address(Value, CharUnits::fromQuantity(Alignment));
  2325. }
  2326. };
  2327. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  2328. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  2329. /// protectFromPeepholes - Protect a value that we're intending to
  2330. /// store to the side, but which will probably be used later, from
  2331. /// aggressive peepholing optimizations that might delete it.
  2332. ///
  2333. /// Pass the result to unprotectFromPeepholes to declare that
  2334. /// protection is no longer required.
  2335. ///
  2336. /// There's no particular reason why this shouldn't apply to
  2337. /// l-values, it's just that no existing peepholes work on pointers.
  2338. PeepholeProtection protectFromPeepholes(RValue rvalue);
  2339. void unprotectFromPeepholes(PeepholeProtection protection);
  2340. void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
  2341. llvm::Value *OffsetValue = nullptr) {
  2342. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  2343. OffsetValue);
  2344. }
  2345. //===--------------------------------------------------------------------===//
  2346. // Statement Emission
  2347. //===--------------------------------------------------------------------===//
  2348. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  2349. void EmitStopPoint(const Stmt *S);
  2350. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  2351. /// this function even if there is no current insertion point.
  2352. ///
  2353. /// This function may clear the current insertion point; callers should use
  2354. /// EnsureInsertPoint if they wish to subsequently generate code without first
  2355. /// calling EmitBlock, EmitBranch, or EmitStmt.
  2356. void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
  2357. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  2358. /// necessarily require an insertion point or debug information; typically
  2359. /// because the statement amounts to a jump or a container of other
  2360. /// statements.
  2361. ///
  2362. /// \return True if the statement was handled.
  2363. bool EmitSimpleStmt(const Stmt *S);
  2364. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  2365. AggValueSlot AVS = AggValueSlot::ignored());
  2366. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  2367. bool GetLast = false,
  2368. AggValueSlot AVS =
  2369. AggValueSlot::ignored());
  2370. /// EmitLabel - Emit the block for the given label. It is legal to call this
  2371. /// function even if there is no current insertion point.
  2372. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  2373. void EmitLabelStmt(const LabelStmt &S);
  2374. void EmitAttributedStmt(const AttributedStmt &S);
  2375. void EmitGotoStmt(const GotoStmt &S);
  2376. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  2377. void EmitIfStmt(const IfStmt &S);
  2378. void EmitWhileStmt(const WhileStmt &S,
  2379. ArrayRef<const Attr *> Attrs = None);
  2380. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  2381. void EmitForStmt(const ForStmt &S,
  2382. ArrayRef<const Attr *> Attrs = None);
  2383. void EmitReturnStmt(const ReturnStmt &S);
  2384. void EmitDeclStmt(const DeclStmt &S);
  2385. void EmitBreakStmt(const BreakStmt &S);
  2386. void EmitContinueStmt(const ContinueStmt &S);
  2387. void EmitSwitchStmt(const SwitchStmt &S);
  2388. void EmitDefaultStmt(const DefaultStmt &S);
  2389. void EmitCaseStmt(const CaseStmt &S);
  2390. void EmitCaseStmtRange(const CaseStmt &S);
  2391. void EmitAsmStmt(const AsmStmt &S);
  2392. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  2393. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  2394. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  2395. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  2396. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  2397. void EmitCoroutineBody(const CoroutineBodyStmt &S);
  2398. void EmitCoreturnStmt(const CoreturnStmt &S);
  2399. RValue EmitCoawaitExpr(const CoawaitExpr &E,
  2400. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2401. bool ignoreResult = false);
  2402. LValue EmitCoawaitLValue(const CoawaitExpr *E);
  2403. RValue EmitCoyieldExpr(const CoyieldExpr &E,
  2404. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2405. bool ignoreResult = false);
  2406. LValue EmitCoyieldLValue(const CoyieldExpr *E);
  2407. RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
  2408. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2409. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2410. void EmitCXXTryStmt(const CXXTryStmt &S);
  2411. void EmitSEHTryStmt(const SEHTryStmt &S);
  2412. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  2413. void EnterSEHTryStmt(const SEHTryStmt &S);
  2414. void ExitSEHTryStmt(const SEHTryStmt &S);
  2415. void pushSEHCleanup(CleanupKind kind,
  2416. llvm::Function *FinallyFunc);
  2417. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  2418. const Stmt *OutlinedStmt);
  2419. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  2420. const SEHExceptStmt &Except);
  2421. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  2422. const SEHFinallyStmt &Finally);
  2423. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  2424. llvm::Value *ParentFP,
  2425. llvm::Value *EntryEBP);
  2426. llvm::Value *EmitSEHExceptionCode();
  2427. llvm::Value *EmitSEHExceptionInfo();
  2428. llvm::Value *EmitSEHAbnormalTermination();
  2429. /// Emit simple code for OpenMP directives in Simd-only mode.
  2430. void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
  2431. /// Scan the outlined statement for captures from the parent function. For
  2432. /// each capture, mark the capture as escaped and emit a call to
  2433. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  2434. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  2435. bool IsFilter);
  2436. /// Recovers the address of a local in a parent function. ParentVar is the
  2437. /// address of the variable used in the immediate parent function. It can
  2438. /// either be an alloca or a call to llvm.localrecover if there are nested
  2439. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  2440. /// frame.
  2441. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  2442. Address ParentVar,
  2443. llvm::Value *ParentFP);
  2444. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  2445. ArrayRef<const Attr *> Attrs = None);
  2446. /// Controls insertion of cancellation exit blocks in worksharing constructs.
  2447. class OMPCancelStackRAII {
  2448. CodeGenFunction &CGF;
  2449. public:
  2450. OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  2451. bool HasCancel)
  2452. : CGF(CGF) {
  2453. CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
  2454. }
  2455. ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
  2456. };
  2457. /// Returns calculated size of the specified type.
  2458. llvm::Value *getTypeSize(QualType Ty);
  2459. LValue InitCapturedStruct(const CapturedStmt &S);
  2460. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  2461. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  2462. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  2463. llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
  2464. void GenerateOpenMPCapturedVars(const CapturedStmt &S,
  2465. SmallVectorImpl<llvm::Value *> &CapturedVars);
  2466. void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
  2467. SourceLocation Loc);
  2468. /// Perform element by element copying of arrays with type \a
  2469. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  2470. /// generated by \a CopyGen.
  2471. ///
  2472. /// \param DestAddr Address of the destination array.
  2473. /// \param SrcAddr Address of the source array.
  2474. /// \param OriginalType Type of destination and source arrays.
  2475. /// \param CopyGen Copying procedure that copies value of single array element
  2476. /// to another single array element.
  2477. void EmitOMPAggregateAssign(
  2478. Address DestAddr, Address SrcAddr, QualType OriginalType,
  2479. const llvm::function_ref<void(Address, Address)> CopyGen);
  2480. /// Emit proper copying of data from one variable to another.
  2481. ///
  2482. /// \param OriginalType Original type of the copied variables.
  2483. /// \param DestAddr Destination address.
  2484. /// \param SrcAddr Source address.
  2485. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  2486. /// type of the base array element).
  2487. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  2488. /// the base array element).
  2489. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  2490. /// DestVD.
  2491. void EmitOMPCopy(QualType OriginalType,
  2492. Address DestAddr, Address SrcAddr,
  2493. const VarDecl *DestVD, const VarDecl *SrcVD,
  2494. const Expr *Copy);
  2495. /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  2496. /// \a X = \a E \a BO \a E.
  2497. ///
  2498. /// \param X Value to be updated.
  2499. /// \param E Update value.
  2500. /// \param BO Binary operation for update operation.
  2501. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  2502. /// expression, false otherwise.
  2503. /// \param AO Atomic ordering of the generated atomic instructions.
  2504. /// \param CommonGen Code generator for complex expressions that cannot be
  2505. /// expressed through atomicrmw instruction.
  2506. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  2507. /// generated, <false, RValue::get(nullptr)> otherwise.
  2508. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  2509. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  2510. llvm::AtomicOrdering AO, SourceLocation Loc,
  2511. const llvm::function_ref<RValue(RValue)> CommonGen);
  2512. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  2513. OMPPrivateScope &PrivateScope);
  2514. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  2515. OMPPrivateScope &PrivateScope);
  2516. void EmitOMPUseDevicePtrClause(
  2517. const OMPClause &C, OMPPrivateScope &PrivateScope,
  2518. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  2519. /// Emit code for copyin clause in \a D directive. The next code is
  2520. /// generated at the start of outlined functions for directives:
  2521. /// \code
  2522. /// threadprivate_var1 = master_threadprivate_var1;
  2523. /// operator=(threadprivate_var2, master_threadprivate_var2);
  2524. /// ...
  2525. /// __kmpc_barrier(&loc, global_tid);
  2526. /// \endcode
  2527. ///
  2528. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  2529. /// \returns true if at least one copyin variable is found, false otherwise.
  2530. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  2531. /// Emit initial code for lastprivate variables. If some variable is
  2532. /// not also firstprivate, then the default initialization is used. Otherwise
  2533. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  2534. /// method.
  2535. ///
  2536. /// \param D Directive that may have 'lastprivate' directives.
  2537. /// \param PrivateScope Private scope for capturing lastprivate variables for
  2538. /// proper codegen in internal captured statement.
  2539. ///
  2540. /// \returns true if there is at least one lastprivate variable, false
  2541. /// otherwise.
  2542. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  2543. OMPPrivateScope &PrivateScope);
  2544. /// Emit final copying of lastprivate values to original variables at
  2545. /// the end of the worksharing or simd directive.
  2546. ///
  2547. /// \param D Directive that has at least one 'lastprivate' directives.
  2548. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  2549. /// it is the last iteration of the loop code in associated directive, or to
  2550. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  2551. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  2552. bool NoFinals,
  2553. llvm::Value *IsLastIterCond = nullptr);
  2554. /// Emit initial code for linear clauses.
  2555. void EmitOMPLinearClause(const OMPLoopDirective &D,
  2556. CodeGenFunction::OMPPrivateScope &PrivateScope);
  2557. /// Emit final code for linear clauses.
  2558. /// \param CondGen Optional conditional code for final part of codegen for
  2559. /// linear clause.
  2560. void EmitOMPLinearClauseFinal(
  2561. const OMPLoopDirective &D,
  2562. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  2563. /// Emit initial code for reduction variables. Creates reduction copies
  2564. /// and initializes them with the values according to OpenMP standard.
  2565. ///
  2566. /// \param D Directive (possibly) with the 'reduction' clause.
  2567. /// \param PrivateScope Private scope for capturing reduction variables for
  2568. /// proper codegen in internal captured statement.
  2569. ///
  2570. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  2571. OMPPrivateScope &PrivateScope);
  2572. /// Emit final update of reduction values to original variables at
  2573. /// the end of the directive.
  2574. ///
  2575. /// \param D Directive that has at least one 'reduction' directives.
  2576. /// \param ReductionKind The kind of reduction to perform.
  2577. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
  2578. const OpenMPDirectiveKind ReductionKind);
  2579. /// Emit initial code for linear variables. Creates private copies
  2580. /// and initializes them with the values according to OpenMP standard.
  2581. ///
  2582. /// \param D Directive (possibly) with the 'linear' clause.
  2583. /// \return true if at least one linear variable is found that should be
  2584. /// initialized with the value of the original variable, false otherwise.
  2585. bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  2586. typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
  2587. llvm::Value * /*OutlinedFn*/,
  2588. const OMPTaskDataTy & /*Data*/)>
  2589. TaskGenTy;
  2590. void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2591. const OpenMPDirectiveKind CapturedRegion,
  2592. const RegionCodeGenTy &BodyGen,
  2593. const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
  2594. struct OMPTargetDataInfo {
  2595. Address BasePointersArray = Address::invalid();
  2596. Address PointersArray = Address::invalid();
  2597. Address SizesArray = Address::invalid();
  2598. unsigned NumberOfTargetItems = 0;
  2599. explicit OMPTargetDataInfo() = default;
  2600. OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
  2601. Address SizesArray, unsigned NumberOfTargetItems)
  2602. : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
  2603. SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {}
  2604. };
  2605. void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
  2606. const RegionCodeGenTy &BodyGen,
  2607. OMPTargetDataInfo &InputInfo);
  2608. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  2609. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  2610. void EmitOMPForDirective(const OMPForDirective &S);
  2611. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  2612. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  2613. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  2614. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  2615. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  2616. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  2617. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  2618. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  2619. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  2620. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  2621. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  2622. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  2623. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  2624. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  2625. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  2626. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  2627. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  2628. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  2629. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  2630. void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
  2631. void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
  2632. void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
  2633. void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
  2634. void
  2635. EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
  2636. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  2637. void
  2638. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  2639. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  2640. void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
  2641. void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
  2642. void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
  2643. void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
  2644. void EmitOMPDistributeParallelForDirective(
  2645. const OMPDistributeParallelForDirective &S);
  2646. void EmitOMPDistributeParallelForSimdDirective(
  2647. const OMPDistributeParallelForSimdDirective &S);
  2648. void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
  2649. void EmitOMPTargetParallelForSimdDirective(
  2650. const OMPTargetParallelForSimdDirective &S);
  2651. void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
  2652. void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
  2653. void
  2654. EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
  2655. void EmitOMPTeamsDistributeParallelForSimdDirective(
  2656. const OMPTeamsDistributeParallelForSimdDirective &S);
  2657. void EmitOMPTeamsDistributeParallelForDirective(
  2658. const OMPTeamsDistributeParallelForDirective &S);
  2659. void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
  2660. void EmitOMPTargetTeamsDistributeDirective(
  2661. const OMPTargetTeamsDistributeDirective &S);
  2662. void EmitOMPTargetTeamsDistributeParallelForDirective(
  2663. const OMPTargetTeamsDistributeParallelForDirective &S);
  2664. void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  2665. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  2666. void EmitOMPTargetTeamsDistributeSimdDirective(
  2667. const OMPTargetTeamsDistributeSimdDirective &S);
  2668. /// Emit device code for the target directive.
  2669. static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  2670. StringRef ParentName,
  2671. const OMPTargetDirective &S);
  2672. static void
  2673. EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2674. const OMPTargetParallelDirective &S);
  2675. /// Emit device code for the target parallel for directive.
  2676. static void EmitOMPTargetParallelForDeviceFunction(
  2677. CodeGenModule &CGM, StringRef ParentName,
  2678. const OMPTargetParallelForDirective &S);
  2679. /// Emit device code for the target parallel for simd directive.
  2680. static void EmitOMPTargetParallelForSimdDeviceFunction(
  2681. CodeGenModule &CGM, StringRef ParentName,
  2682. const OMPTargetParallelForSimdDirective &S);
  2683. /// Emit device code for the target teams directive.
  2684. static void
  2685. EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2686. const OMPTargetTeamsDirective &S);
  2687. /// Emit device code for the target teams distribute directive.
  2688. static void EmitOMPTargetTeamsDistributeDeviceFunction(
  2689. CodeGenModule &CGM, StringRef ParentName,
  2690. const OMPTargetTeamsDistributeDirective &S);
  2691. /// Emit device code for the target teams distribute simd directive.
  2692. static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  2693. CodeGenModule &CGM, StringRef ParentName,
  2694. const OMPTargetTeamsDistributeSimdDirective &S);
  2695. /// Emit device code for the target simd directive.
  2696. static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
  2697. StringRef ParentName,
  2698. const OMPTargetSimdDirective &S);
  2699. /// Emit device code for the target teams distribute parallel for simd
  2700. /// directive.
  2701. static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  2702. CodeGenModule &CGM, StringRef ParentName,
  2703. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  2704. static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  2705. CodeGenModule &CGM, StringRef ParentName,
  2706. const OMPTargetTeamsDistributeParallelForDirective &S);
  2707. /// Emit inner loop of the worksharing/simd construct.
  2708. ///
  2709. /// \param S Directive, for which the inner loop must be emitted.
  2710. /// \param RequiresCleanup true, if directive has some associated private
  2711. /// variables.
  2712. /// \param LoopCond Bollean condition for loop continuation.
  2713. /// \param IncExpr Increment expression for loop control variable.
  2714. /// \param BodyGen Generator for the inner body of the inner loop.
  2715. /// \param PostIncGen Genrator for post-increment code (required for ordered
  2716. /// loop directvies).
  2717. void EmitOMPInnerLoop(
  2718. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  2719. const Expr *IncExpr,
  2720. const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
  2721. const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
  2722. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  2723. /// Emit initial code for loop counters of loop-based directives.
  2724. void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
  2725. OMPPrivateScope &LoopScope);
  2726. /// Helper for the OpenMP loop directives.
  2727. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  2728. /// Emit code for the worksharing loop-based directive.
  2729. /// \return true, if this construct has any lastprivate clause, false -
  2730. /// otherwise.
  2731. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
  2732. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  2733. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2734. /// Emit code for the distribute loop-based directive.
  2735. void EmitOMPDistributeLoop(const OMPLoopDirective &S,
  2736. const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
  2737. /// Helpers for the OpenMP loop directives.
  2738. void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
  2739. void EmitOMPSimdFinal(
  2740. const OMPLoopDirective &D,
  2741. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
  2742. /// Emits the lvalue for the expression with possibly captured variable.
  2743. LValue EmitOMPSharedLValue(const Expr *E);
  2744. private:
  2745. /// Helpers for blocks.
  2746. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  2747. /// struct with the values to be passed to the OpenMP loop-related functions
  2748. struct OMPLoopArguments {
  2749. /// loop lower bound
  2750. Address LB = Address::invalid();
  2751. /// loop upper bound
  2752. Address UB = Address::invalid();
  2753. /// loop stride
  2754. Address ST = Address::invalid();
  2755. /// isLastIteration argument for runtime functions
  2756. Address IL = Address::invalid();
  2757. /// Chunk value generated by sema
  2758. llvm::Value *Chunk = nullptr;
  2759. /// EnsureUpperBound
  2760. Expr *EUB = nullptr;
  2761. /// IncrementExpression
  2762. Expr *IncExpr = nullptr;
  2763. /// Loop initialization
  2764. Expr *Init = nullptr;
  2765. /// Loop exit condition
  2766. Expr *Cond = nullptr;
  2767. /// Update of LB after a whole chunk has been executed
  2768. Expr *NextLB = nullptr;
  2769. /// Update of UB after a whole chunk has been executed
  2770. Expr *NextUB = nullptr;
  2771. OMPLoopArguments() = default;
  2772. OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
  2773. llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
  2774. Expr *IncExpr = nullptr, Expr *Init = nullptr,
  2775. Expr *Cond = nullptr, Expr *NextLB = nullptr,
  2776. Expr *NextUB = nullptr)
  2777. : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
  2778. IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
  2779. NextUB(NextUB) {}
  2780. };
  2781. void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
  2782. const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
  2783. const OMPLoopArguments &LoopArgs,
  2784. const CodeGenLoopTy &CodeGenLoop,
  2785. const CodeGenOrderedTy &CodeGenOrdered);
  2786. void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
  2787. bool IsMonotonic, const OMPLoopDirective &S,
  2788. OMPPrivateScope &LoopScope, bool Ordered,
  2789. const OMPLoopArguments &LoopArgs,
  2790. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2791. void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
  2792. const OMPLoopDirective &S,
  2793. OMPPrivateScope &LoopScope,
  2794. const OMPLoopArguments &LoopArgs,
  2795. const CodeGenLoopTy &CodeGenLoopContent);
  2796. /// Emit code for sections directive.
  2797. void EmitSections(const OMPExecutableDirective &S);
  2798. public:
  2799. //===--------------------------------------------------------------------===//
  2800. // LValue Expression Emission
  2801. //===--------------------------------------------------------------------===//
  2802. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  2803. RValue GetUndefRValue(QualType Ty);
  2804. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  2805. /// and issue an ErrorUnsupported style diagnostic (using the
  2806. /// provided Name).
  2807. RValue EmitUnsupportedRValue(const Expr *E,
  2808. const char *Name);
  2809. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  2810. /// an ErrorUnsupported style diagnostic (using the provided Name).
  2811. LValue EmitUnsupportedLValue(const Expr *E,
  2812. const char *Name);
  2813. /// EmitLValue - Emit code to compute a designator that specifies the location
  2814. /// of the expression.
  2815. ///
  2816. /// This can return one of two things: a simple address or a bitfield
  2817. /// reference. In either case, the LLVM Value* in the LValue structure is
  2818. /// guaranteed to be an LLVM pointer type.
  2819. ///
  2820. /// If this returns a bitfield reference, nothing about the pointee type of
  2821. /// the LLVM value is known: For example, it may not be a pointer to an
  2822. /// integer.
  2823. ///
  2824. /// If this returns a normal address, and if the lvalue's C type is fixed
  2825. /// size, this method guarantees that the returned pointer type will point to
  2826. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  2827. /// variable length type, this is not possible.
  2828. ///
  2829. LValue EmitLValue(const Expr *E);
  2830. /// Same as EmitLValue but additionally we generate checking code to
  2831. /// guard against undefined behavior. This is only suitable when we know
  2832. /// that the address will be used to access the object.
  2833. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  2834. RValue convertTempToRValue(Address addr, QualType type,
  2835. SourceLocation Loc);
  2836. void EmitAtomicInit(Expr *E, LValue lvalue);
  2837. bool LValueIsSuitableForInlineAtomic(LValue Src);
  2838. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  2839. AggValueSlot Slot = AggValueSlot::ignored());
  2840. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  2841. llvm::AtomicOrdering AO, bool IsVolatile = false,
  2842. AggValueSlot slot = AggValueSlot::ignored());
  2843. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  2844. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  2845. bool IsVolatile, bool isInit);
  2846. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  2847. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  2848. llvm::AtomicOrdering Success =
  2849. llvm::AtomicOrdering::SequentiallyConsistent,
  2850. llvm::AtomicOrdering Failure =
  2851. llvm::AtomicOrdering::SequentiallyConsistent,
  2852. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  2853. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  2854. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  2855. bool IsVolatile);
  2856. /// EmitToMemory - Change a scalar value from its value
  2857. /// representation to its in-memory representation.
  2858. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  2859. /// EmitFromMemory - Change a scalar value from its memory
  2860. /// representation to its value representation.
  2861. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  2862. /// Check if the scalar \p Value is within the valid range for the given
  2863. /// type \p Ty.
  2864. ///
  2865. /// Returns true if a check is needed (even if the range is unknown).
  2866. bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  2867. SourceLocation Loc);
  2868. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2869. /// care to appropriately convert from the memory representation to
  2870. /// the LLVM value representation.
  2871. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2872. SourceLocation Loc,
  2873. AlignmentSource Source = AlignmentSource::Type,
  2874. bool isNontemporal = false) {
  2875. return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
  2876. CGM.getTBAAAccessInfo(Ty), isNontemporal);
  2877. }
  2878. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2879. SourceLocation Loc, LValueBaseInfo BaseInfo,
  2880. TBAAAccessInfo TBAAInfo,
  2881. bool isNontemporal = false);
  2882. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2883. /// care to appropriately convert from the memory representation to
  2884. /// the LLVM value representation. The l-value must be a simple
  2885. /// l-value.
  2886. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  2887. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2888. /// care to appropriately convert from the memory representation to
  2889. /// the LLVM value representation.
  2890. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2891. bool Volatile, QualType Ty,
  2892. AlignmentSource Source = AlignmentSource::Type,
  2893. bool isInit = false, bool isNontemporal = false) {
  2894. EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
  2895. CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
  2896. }
  2897. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2898. bool Volatile, QualType Ty,
  2899. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
  2900. bool isInit = false, bool isNontemporal = false);
  2901. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2902. /// care to appropriately convert from the memory representation to
  2903. /// the LLVM value representation. The l-value must be a simple
  2904. /// l-value. The isInit flag indicates whether this is an initialization.
  2905. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2906. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2907. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2908. /// this method emits the address of the lvalue, then loads the result as an
  2909. /// rvalue, returning the rvalue.
  2910. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2911. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2912. RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
  2913. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2914. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2915. /// lvalue, where both are guaranteed to the have the same type, and that type
  2916. /// is 'Ty'.
  2917. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2918. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2919. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2920. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2921. /// as EmitStoreThroughLValue.
  2922. ///
  2923. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2924. /// bit-field contents after the store, appropriate for use as the result of
  2925. /// an assignment to the bit-field.
  2926. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2927. llvm::Value **Result=nullptr);
  2928. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2929. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2930. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2931. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2932. llvm::Value *&Result);
  2933. // Note: only available for agg return types
  2934. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2935. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2936. // Note: only available for agg return types
  2937. LValue EmitCallExprLValue(const CallExpr *E);
  2938. // Note: only available for agg return types
  2939. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2940. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2941. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2942. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2943. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2944. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2945. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2946. bool Accessed = false);
  2947. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  2948. bool IsLowerBound = true);
  2949. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2950. LValue EmitMemberExpr(const MemberExpr *E);
  2951. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2952. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2953. LValue EmitInitListLValue(const InitListExpr *E);
  2954. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2955. LValue EmitCastLValue(const CastExpr *E);
  2956. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2957. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2958. Address EmitExtVectorElementLValue(LValue V);
  2959. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2960. Address EmitArrayToPointerDecay(const Expr *Array,
  2961. LValueBaseInfo *BaseInfo = nullptr,
  2962. TBAAAccessInfo *TBAAInfo = nullptr);
  2963. class ConstantEmission {
  2964. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2965. ConstantEmission(llvm::Constant *C, bool isReference)
  2966. : ValueAndIsReference(C, isReference) {}
  2967. public:
  2968. ConstantEmission() {}
  2969. static ConstantEmission forReference(llvm::Constant *C) {
  2970. return ConstantEmission(C, true);
  2971. }
  2972. static ConstantEmission forValue(llvm::Constant *C) {
  2973. return ConstantEmission(C, false);
  2974. }
  2975. explicit operator bool() const {
  2976. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2977. }
  2978. bool isReference() const { return ValueAndIsReference.getInt(); }
  2979. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2980. assert(isReference());
  2981. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2982. refExpr->getType());
  2983. }
  2984. llvm::Constant *getValue() const {
  2985. assert(!isReference());
  2986. return ValueAndIsReference.getPointer();
  2987. }
  2988. };
  2989. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2990. ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
  2991. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2992. AggValueSlot slot = AggValueSlot::ignored());
  2993. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2994. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2995. const ObjCIvarDecl *Ivar);
  2996. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2997. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2998. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2999. /// if the Field is a reference, this will return the address of the reference
  3000. /// and not the address of the value stored in the reference.
  3001. LValue EmitLValueForFieldInitialization(LValue Base,
  3002. const FieldDecl* Field);
  3003. LValue EmitLValueForIvar(QualType ObjectTy,
  3004. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  3005. unsigned CVRQualifiers);
  3006. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  3007. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  3008. LValue EmitLambdaLValue(const LambdaExpr *E);
  3009. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  3010. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  3011. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  3012. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  3013. LValue EmitStmtExprLValue(const StmtExpr *E);
  3014. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  3015. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  3016. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
  3017. //===--------------------------------------------------------------------===//
  3018. // Scalar Expression Emission
  3019. //===--------------------------------------------------------------------===//
  3020. /// EmitCall - Generate a call of the given function, expecting the given
  3021. /// result type, and using the given argument list which specifies both the
  3022. /// LLVM arguments and the types they were derived from.
  3023. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3024. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3025. llvm::Instruction **callOrInvoke, SourceLocation Loc);
  3026. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  3027. ReturnValueSlot ReturnValue, const CallArgList &Args,
  3028. llvm::Instruction **callOrInvoke = nullptr) {
  3029. return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
  3030. SourceLocation());
  3031. }
  3032. RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
  3033. ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
  3034. RValue EmitCallExpr(const CallExpr *E,
  3035. ReturnValueSlot ReturnValue = ReturnValueSlot());
  3036. RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3037. CGCallee EmitCallee(const Expr *E);
  3038. void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
  3039. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  3040. const Twine &name = "");
  3041. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  3042. ArrayRef<llvm::Value*> args,
  3043. const Twine &name = "");
  3044. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  3045. const Twine &name = "");
  3046. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  3047. ArrayRef<llvm::Value*> args,
  3048. const Twine &name = "");
  3049. SmallVector<llvm::OperandBundleDef, 1>
  3050. getBundlesForFunclet(llvm::Value *Callee);
  3051. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  3052. ArrayRef<llvm::Value *> Args,
  3053. const Twine &Name = "");
  3054. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  3055. ArrayRef<llvm::Value*> args,
  3056. const Twine &name = "");
  3057. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  3058. const Twine &name = "");
  3059. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  3060. ArrayRef<llvm::Value*> args);
  3061. CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  3062. NestedNameSpecifier *Qual,
  3063. llvm::Type *Ty);
  3064. CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  3065. CXXDtorType Type,
  3066. const CXXRecordDecl *RD);
  3067. // Return the copy constructor name with the prefix "__copy_constructor_"
  3068. // removed.
  3069. static std::string getNonTrivialCopyConstructorStr(QualType QT,
  3070. CharUnits Alignment,
  3071. bool IsVolatile,
  3072. ASTContext &Ctx);
  3073. // Return the destructor name with the prefix "__destructor_" removed.
  3074. static std::string getNonTrivialDestructorStr(QualType QT,
  3075. CharUnits Alignment,
  3076. bool IsVolatile,
  3077. ASTContext &Ctx);
  3078. // These functions emit calls to the special functions of non-trivial C
  3079. // structs.
  3080. void defaultInitNonTrivialCStructVar(LValue Dst);
  3081. void callCStructDefaultConstructor(LValue Dst);
  3082. void callCStructDestructor(LValue Dst);
  3083. void callCStructCopyConstructor(LValue Dst, LValue Src);
  3084. void callCStructMoveConstructor(LValue Dst, LValue Src);
  3085. void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
  3086. void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
  3087. RValue
  3088. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
  3089. const CGCallee &Callee,
  3090. ReturnValueSlot ReturnValue, llvm::Value *This,
  3091. llvm::Value *ImplicitParam,
  3092. QualType ImplicitParamTy, const CallExpr *E,
  3093. CallArgList *RtlArgs);
  3094. RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  3095. const CGCallee &Callee,
  3096. llvm::Value *This, llvm::Value *ImplicitParam,
  3097. QualType ImplicitParamTy, const CallExpr *E,
  3098. StructorType Type);
  3099. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  3100. ReturnValueSlot ReturnValue);
  3101. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  3102. const CXXMethodDecl *MD,
  3103. ReturnValueSlot ReturnValue,
  3104. bool HasQualifier,
  3105. NestedNameSpecifier *Qualifier,
  3106. bool IsArrow, const Expr *Base);
  3107. // Compute the object pointer.
  3108. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  3109. llvm::Value *memberPtr,
  3110. const MemberPointerType *memberPtrType,
  3111. LValueBaseInfo *BaseInfo = nullptr,
  3112. TBAAAccessInfo *TBAAInfo = nullptr);
  3113. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  3114. ReturnValueSlot ReturnValue);
  3115. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  3116. const CXXMethodDecl *MD,
  3117. ReturnValueSlot ReturnValue);
  3118. RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  3119. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  3120. ReturnValueSlot ReturnValue);
  3121. RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
  3122. ReturnValueSlot ReturnValue);
  3123. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  3124. unsigned BuiltinID, const CallExpr *E,
  3125. ReturnValueSlot ReturnValue);
  3126. RValue emitRotate(const CallExpr *E, bool IsRotateRight);
  3127. /// Emit IR for __builtin_os_log_format.
  3128. RValue emitBuiltinOSLogFormat(const CallExpr &E);
  3129. llvm::Function *generateBuiltinOSLogHelperFunction(
  3130. const analyze_os_log::OSLogBufferLayout &Layout,
  3131. CharUnits BufferAlignment);
  3132. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  3133. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  3134. /// is unhandled by the current target.
  3135. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3136. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  3137. const llvm::CmpInst::Predicate Fp,
  3138. const llvm::CmpInst::Predicate Ip,
  3139. const llvm::Twine &Name = "");
  3140. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3141. llvm::Triple::ArchType Arch);
  3142. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  3143. unsigned LLVMIntrinsic,
  3144. unsigned AltLLVMIntrinsic,
  3145. const char *NameHint,
  3146. unsigned Modifier,
  3147. const CallExpr *E,
  3148. SmallVectorImpl<llvm::Value *> &Ops,
  3149. Address PtrOp0, Address PtrOp1,
  3150. llvm::Triple::ArchType Arch);
  3151. llvm::Value *EmitISOVolatileLoad(const CallExpr *E);
  3152. llvm::Value *EmitISOVolatileStore(const CallExpr *E);
  3153. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  3154. unsigned Modifier, llvm::Type *ArgTy,
  3155. const CallExpr *E);
  3156. llvm::Value *EmitNeonCall(llvm::Function *F,
  3157. SmallVectorImpl<llvm::Value*> &O,
  3158. const char *name,
  3159. unsigned shift = 0, bool rightshift = false);
  3160. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  3161. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  3162. bool negateForRightShift);
  3163. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  3164. llvm::Type *Ty, bool usgn, const char *name);
  3165. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  3166. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
  3167. llvm::Triple::ArchType Arch);
  3168. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  3169. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3170. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3171. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3172. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3173. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3174. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  3175. const CallExpr *E);
  3176. llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  3177. private:
  3178. enum class MSVCIntrin;
  3179. public:
  3180. llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
  3181. llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
  3182. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  3183. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  3184. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  3185. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  3186. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  3187. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  3188. const ObjCMethodDecl *MethodWithObjects);
  3189. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  3190. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  3191. ReturnValueSlot Return = ReturnValueSlot());
  3192. /// Retrieves the default cleanup kind for an ARC cleanup.
  3193. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  3194. CleanupKind getARCCleanupKind() {
  3195. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  3196. ? NormalAndEHCleanup : NormalCleanup;
  3197. }
  3198. // ARC primitives.
  3199. void EmitARCInitWeak(Address addr, llvm::Value *value);
  3200. void EmitARCDestroyWeak(Address addr);
  3201. llvm::Value *EmitARCLoadWeak(Address addr);
  3202. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  3203. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  3204. void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3205. void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
  3206. void EmitARCCopyWeak(Address dst, Address src);
  3207. void EmitARCMoveWeak(Address dst, Address src);
  3208. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  3209. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  3210. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  3211. bool resultIgnored);
  3212. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  3213. bool resultIgnored);
  3214. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  3215. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  3216. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  3217. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  3218. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  3219. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  3220. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  3221. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  3222. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  3223. llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
  3224. std::pair<LValue,llvm::Value*>
  3225. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  3226. std::pair<LValue,llvm::Value*>
  3227. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  3228. std::pair<LValue,llvm::Value*>
  3229. EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
  3230. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  3231. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  3232. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  3233. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  3234. llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
  3235. bool allowUnsafeClaim);
  3236. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  3237. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  3238. llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
  3239. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  3240. static Destroyer destroyARCStrongImprecise;
  3241. static Destroyer destroyARCStrongPrecise;
  3242. static Destroyer destroyARCWeak;
  3243. static Destroyer emitARCIntrinsicUse;
  3244. static Destroyer destroyNonTrivialCStruct;
  3245. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  3246. llvm::Value *EmitObjCAutoreleasePoolPush();
  3247. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  3248. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  3249. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  3250. /// Emits a reference binding to the passed in expression.
  3251. RValue EmitReferenceBindingToExpr(const Expr *E);
  3252. //===--------------------------------------------------------------------===//
  3253. // Expression Emission
  3254. //===--------------------------------------------------------------------===//
  3255. // Expressions are broken into three classes: scalar, complex, aggregate.
  3256. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  3257. /// scalar type, returning the result.
  3258. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  3259. /// Emit a conversion from the specified type to the specified destination
  3260. /// type, both of which are LLVM scalar types.
  3261. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  3262. QualType DstTy, SourceLocation Loc);
  3263. /// Emit a conversion from the specified complex type to the specified
  3264. /// destination type, where the destination type is an LLVM scalar type.
  3265. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  3266. QualType DstTy,
  3267. SourceLocation Loc);
  3268. /// EmitAggExpr - Emit the computation of the specified expression
  3269. /// of aggregate type. The result is computed into the given slot,
  3270. /// which may be null to indicate that the value is not needed.
  3271. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  3272. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  3273. /// aggregate type into a temporary LValue.
  3274. LValue EmitAggExprToLValue(const Expr *E);
  3275. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  3276. /// make sure it survives garbage collection until this point.
  3277. void EmitExtendGCLifetime(llvm::Value *object);
  3278. /// EmitComplexExpr - Emit the computation of the specified expression of
  3279. /// complex type, returning the result.
  3280. ComplexPairTy EmitComplexExpr(const Expr *E,
  3281. bool IgnoreReal = false,
  3282. bool IgnoreImag = false);
  3283. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  3284. /// type and place its result into the specified l-value.
  3285. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  3286. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  3287. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  3288. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  3289. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  3290. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  3291. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  3292. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  3293. /// global variable that has already been created for it. If the initializer
  3294. /// has a different type than GV does, this may free GV and return a different
  3295. /// one. Otherwise it just returns GV.
  3296. llvm::GlobalVariable *
  3297. AddInitializerToStaticVarDecl(const VarDecl &D,
  3298. llvm::GlobalVariable *GV);
  3299. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  3300. /// variable with global storage.
  3301. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  3302. bool PerformInit);
  3303. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  3304. llvm::Constant *Addr);
  3305. /// Call atexit() with a function that passes the given argument to
  3306. /// the given function.
  3307. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  3308. llvm::Constant *addr);
  3309. /// Call atexit() with function dtorStub.
  3310. void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
  3311. /// Emit code in this function to perform a guarded variable
  3312. /// initialization. Guarded initializations are used when it's not
  3313. /// possible to prove that an initialization will be done exactly
  3314. /// once, e.g. with a static local variable or a static data member
  3315. /// of a class template.
  3316. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  3317. bool PerformInit);
  3318. enum class GuardKind { VariableGuard, TlsGuard };
  3319. /// Emit a branch to select whether or not to perform guarded initialization.
  3320. void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
  3321. llvm::BasicBlock *InitBlock,
  3322. llvm::BasicBlock *NoInitBlock,
  3323. GuardKind Kind, const VarDecl *D);
  3324. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  3325. /// variables.
  3326. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  3327. ArrayRef<llvm::Function *> CXXThreadLocals,
  3328. Address Guard = Address::invalid());
  3329. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  3330. /// variables.
  3331. void GenerateCXXGlobalDtorsFunc(
  3332. llvm::Function *Fn,
  3333. const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
  3334. &DtorsAndObjects);
  3335. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  3336. const VarDecl *D,
  3337. llvm::GlobalVariable *Addr,
  3338. bool PerformInit);
  3339. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  3340. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  3341. void enterFullExpression(const ExprWithCleanups *E) {
  3342. if (E->getNumObjects() == 0) return;
  3343. enterNonTrivialFullExpression(E);
  3344. }
  3345. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  3346. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  3347. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  3348. RValue EmitAtomicExpr(AtomicExpr *E);
  3349. //===--------------------------------------------------------------------===//
  3350. // Annotations Emission
  3351. //===--------------------------------------------------------------------===//
  3352. /// Emit an annotation call (intrinsic or builtin).
  3353. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  3354. llvm::Value *AnnotatedVal,
  3355. StringRef AnnotationStr,
  3356. SourceLocation Location);
  3357. /// Emit local annotations for the local variable V, declared by D.
  3358. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  3359. /// Emit field annotations for the given field & value. Returns the
  3360. /// annotation result.
  3361. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  3362. //===--------------------------------------------------------------------===//
  3363. // Internal Helpers
  3364. //===--------------------------------------------------------------------===//
  3365. /// ContainsLabel - Return true if the statement contains a label in it. If
  3366. /// this statement is not executed normally, it not containing a label means
  3367. /// that we can just remove the code.
  3368. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  3369. /// containsBreak - Return true if the statement contains a break out of it.
  3370. /// If the statement (recursively) contains a switch or loop with a break
  3371. /// inside of it, this is fine.
  3372. static bool containsBreak(const Stmt *S);
  3373. /// Determine if the given statement might introduce a declaration into the
  3374. /// current scope, by being a (possibly-labelled) DeclStmt.
  3375. static bool mightAddDeclToScope(const Stmt *S);
  3376. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3377. /// to a constant, or if it does but contains a label, return false. If it
  3378. /// constant folds return true and set the boolean result in Result.
  3379. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
  3380. bool AllowLabels = false);
  3381. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3382. /// to a constant, or if it does but contains a label, return false. If it
  3383. /// constant folds return true and set the folded value.
  3384. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
  3385. bool AllowLabels = false);
  3386. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  3387. /// if statement) to the specified blocks. Based on the condition, this might
  3388. /// try to simplify the codegen of the conditional based on the branch.
  3389. /// TrueCount should be the number of times we expect the condition to
  3390. /// evaluate to true based on PGO data.
  3391. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  3392. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  3393. /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
  3394. /// nonnull, if \p LHS is marked _Nonnull.
  3395. void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
  3396. /// An enumeration which makes it easier to specify whether or not an
  3397. /// operation is a subtraction.
  3398. enum { NotSubtraction = false, IsSubtraction = true };
  3399. /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
  3400. /// detect undefined behavior when the pointer overflow sanitizer is enabled.
  3401. /// \p SignedIndices indicates whether any of the GEP indices are signed.
  3402. /// \p IsSubtraction indicates whether the expression used to form the GEP
  3403. /// is a subtraction.
  3404. llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
  3405. ArrayRef<llvm::Value *> IdxList,
  3406. bool SignedIndices,
  3407. bool IsSubtraction,
  3408. SourceLocation Loc,
  3409. const Twine &Name = "");
  3410. /// Specifies which type of sanitizer check to apply when handling a
  3411. /// particular builtin.
  3412. enum BuiltinCheckKind {
  3413. BCK_CTZPassedZero,
  3414. BCK_CLZPassedZero,
  3415. };
  3416. /// Emits an argument for a call to a builtin. If the builtin sanitizer is
  3417. /// enabled, a runtime check specified by \p Kind is also emitted.
  3418. llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
  3419. /// Emit a description of a type in a format suitable for passing to
  3420. /// a runtime sanitizer handler.
  3421. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  3422. /// Convert a value into a format suitable for passing to a runtime
  3423. /// sanitizer handler.
  3424. llvm::Value *EmitCheckValue(llvm::Value *V);
  3425. /// Emit a description of a source location in a format suitable for
  3426. /// passing to a runtime sanitizer handler.
  3427. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  3428. /// Create a basic block that will call a handler function in a
  3429. /// sanitizer runtime with the provided arguments, and create a conditional
  3430. /// branch to it.
  3431. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  3432. SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
  3433. ArrayRef<llvm::Value *> DynamicArgs);
  3434. /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
  3435. /// if Cond if false.
  3436. void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
  3437. llvm::ConstantInt *TypeId, llvm::Value *Ptr,
  3438. ArrayRef<llvm::Constant *> StaticArgs);
  3439. /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
  3440. /// checking is enabled. Otherwise, just emit an unreachable instruction.
  3441. void EmitUnreachable(SourceLocation Loc);
  3442. /// Create a basic block that will call the trap intrinsic, and emit a
  3443. /// conditional branch to it, for the -ftrapv checks.
  3444. void EmitTrapCheck(llvm::Value *Checked);
  3445. /// Emit a call to trap or debugtrap and attach function attribute
  3446. /// "trap-func-name" if specified.
  3447. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  3448. /// Emit a stub for the cross-DSO CFI check function.
  3449. void EmitCfiCheckStub();
  3450. /// Emit a cross-DSO CFI failure handling function.
  3451. void EmitCfiCheckFail();
  3452. /// Create a check for a function parameter that may potentially be
  3453. /// declared as non-null.
  3454. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  3455. AbstractCallee AC, unsigned ParmNum);
  3456. /// EmitCallArg - Emit a single call argument.
  3457. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  3458. /// EmitDelegateCallArg - We are performing a delegate call; that
  3459. /// is, the current function is delegating to another one. Produce
  3460. /// a r-value suitable for passing the given parameter.
  3461. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  3462. SourceLocation loc);
  3463. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  3464. /// point operation, expressed as the maximum relative error in ulp.
  3465. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  3466. private:
  3467. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  3468. void EmitReturnOfRValue(RValue RV, QualType Ty);
  3469. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  3470. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  3471. DeferredReplacements;
  3472. /// Set the address of a local variable.
  3473. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  3474. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  3475. LocalDeclMap.insert({VD, Addr});
  3476. }
  3477. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  3478. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  3479. ///
  3480. /// \param AI - The first function argument of the expansion.
  3481. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  3482. SmallVectorImpl<llvm::Value *>::iterator &AI);
  3483. /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
  3484. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  3485. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  3486. void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  3487. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  3488. unsigned &IRCallArgPos);
  3489. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  3490. const Expr *InputExpr, std::string &ConstraintStr);
  3491. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  3492. LValue InputValue, QualType InputType,
  3493. std::string &ConstraintStr,
  3494. SourceLocation Loc);
  3495. /// Attempts to statically evaluate the object size of E. If that
  3496. /// fails, emits code to figure the size of E out for us. This is
  3497. /// pass_object_size aware.
  3498. ///
  3499. /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
  3500. llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
  3501. llvm::IntegerType *ResType,
  3502. llvm::Value *EmittedE);
  3503. /// Emits the size of E, as required by __builtin_object_size. This
  3504. /// function is aware of pass_object_size parameters, and will act accordingly
  3505. /// if E is a parameter with the pass_object_size attribute.
  3506. llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
  3507. llvm::IntegerType *ResType,
  3508. llvm::Value *EmittedE);
  3509. public:
  3510. #ifndef NDEBUG
  3511. // Determine whether the given argument is an Objective-C method
  3512. // that may have type parameters in its signature.
  3513. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  3514. const DeclContext *dc = method->getDeclContext();
  3515. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  3516. return classDecl->getTypeParamListAsWritten();
  3517. }
  3518. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  3519. return catDecl->getTypeParamList();
  3520. }
  3521. return false;
  3522. }
  3523. template<typename T>
  3524. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  3525. #endif
  3526. enum class EvaluationOrder {
  3527. ///! No language constraints on evaluation order.
  3528. Default,
  3529. ///! Language semantics require left-to-right evaluation.
  3530. ForceLeftToRight,
  3531. ///! Language semantics require right-to-left evaluation.
  3532. ForceRightToLeft
  3533. };
  3534. /// EmitCallArgs - Emit call arguments for a function.
  3535. template <typename T>
  3536. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  3537. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3538. AbstractCallee AC = AbstractCallee(),
  3539. unsigned ParamsToSkip = 0,
  3540. EvaluationOrder Order = EvaluationOrder::Default) {
  3541. SmallVector<QualType, 16> ArgTypes;
  3542. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  3543. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  3544. "Can't skip parameters if type info is not provided");
  3545. if (CallArgTypeInfo) {
  3546. #ifndef NDEBUG
  3547. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  3548. #endif
  3549. // First, use the argument types that the type info knows about
  3550. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  3551. E = CallArgTypeInfo->param_type_end();
  3552. I != E; ++I, ++Arg) {
  3553. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  3554. assert((isGenericMethod ||
  3555. ((*I)->isVariablyModifiedType() ||
  3556. (*I).getNonReferenceType()->isObjCRetainableType() ||
  3557. getContext()
  3558. .getCanonicalType((*I).getNonReferenceType())
  3559. .getTypePtr() ==
  3560. getContext()
  3561. .getCanonicalType((*Arg)->getType())
  3562. .getTypePtr())) &&
  3563. "type mismatch in call argument!");
  3564. ArgTypes.push_back(*I);
  3565. }
  3566. }
  3567. // Either we've emitted all the call args, or we have a call to variadic
  3568. // function.
  3569. assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
  3570. CallArgTypeInfo->isVariadic()) &&
  3571. "Extra arguments in non-variadic function!");
  3572. // If we still have any arguments, emit them using the type of the argument.
  3573. for (auto *A : llvm::make_range(Arg, ArgRange.end()))
  3574. ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
  3575. EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
  3576. }
  3577. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  3578. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3579. AbstractCallee AC = AbstractCallee(),
  3580. unsigned ParamsToSkip = 0,
  3581. EvaluationOrder Order = EvaluationOrder::Default);
  3582. /// EmitPointerWithAlignment - Given an expression with a pointer type,
  3583. /// emit the value and compute our best estimate of the alignment of the
  3584. /// pointee.
  3585. ///
  3586. /// \param BaseInfo - If non-null, this will be initialized with
  3587. /// information about the source of the alignment and the may-alias
  3588. /// attribute. Note that this function will conservatively fall back on
  3589. /// the type when it doesn't recognize the expression and may-alias will
  3590. /// be set to false.
  3591. ///
  3592. /// One reasonable way to use this information is when there's a language
  3593. /// guarantee that the pointer must be aligned to some stricter value, and
  3594. /// we're simply trying to ensure that sufficiently obvious uses of under-
  3595. /// aligned objects don't get miscompiled; for example, a placement new
  3596. /// into the address of a local variable. In such a case, it's quite
  3597. /// reasonable to just ignore the returned alignment when it isn't from an
  3598. /// explicit source.
  3599. Address EmitPointerWithAlignment(const Expr *Addr,
  3600. LValueBaseInfo *BaseInfo = nullptr,
  3601. TBAAAccessInfo *TBAAInfo = nullptr);
  3602. /// If \p E references a parameter with pass_object_size info or a constant
  3603. /// array size modifier, emit the object size divided by the size of \p EltTy.
  3604. /// Otherwise return null.
  3605. llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
  3606. void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
  3607. struct MultiVersionResolverOption {
  3608. llvm::Function *Function;
  3609. struct Conds {
  3610. StringRef Architecture;
  3611. llvm::SmallVector<StringRef, 8> Features;
  3612. Conds(StringRef Arch, ArrayRef<StringRef> Feats)
  3613. : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
  3614. } Conditions;
  3615. MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
  3616. ArrayRef<StringRef> Feats)
  3617. : Function(F), Conditions(Arch, Feats) {}
  3618. };
  3619. // Emits the body of a multiversion function's resolver. Assumes that the
  3620. // options are already sorted in the proper order, with the 'default' option
  3621. // last (if it exists).
  3622. void EmitMultiVersionResolver(llvm::Function *Resolver,
  3623. ArrayRef<MultiVersionResolverOption> Options);
  3624. struct CPUDispatchMultiVersionResolverOption {
  3625. llvm::Function *Function;
  3626. // Note: EmitX86CPUSupports only has 32 bits available, so we store the mask
  3627. // as 32 bits here. When 64-bit support is added to __builtin_cpu_supports,
  3628. // this can be extended to 64 bits.
  3629. uint32_t FeatureMask;
  3630. CPUDispatchMultiVersionResolverOption(llvm::Function *F, uint64_t Mask)
  3631. : Function(F), FeatureMask(static_cast<uint32_t>(Mask)) {}
  3632. bool operator>(const CPUDispatchMultiVersionResolverOption &Other) const {
  3633. return FeatureMask > Other.FeatureMask;
  3634. }
  3635. };
  3636. void EmitCPUDispatchMultiVersionResolver(
  3637. llvm::Function *Resolver,
  3638. ArrayRef<CPUDispatchMultiVersionResolverOption> Options);
  3639. static uint32_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs);
  3640. private:
  3641. QualType getVarArgType(const Expr *Arg);
  3642. void EmitDeclMetadata();
  3643. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  3644. const AutoVarEmission &emission);
  3645. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  3646. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  3647. llvm::Value *EmitX86CpuIs(const CallExpr *E);
  3648. llvm::Value *EmitX86CpuIs(StringRef CPUStr);
  3649. llvm::Value *EmitX86CpuSupports(const CallExpr *E);
  3650. llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
  3651. llvm::Value *EmitX86CpuSupports(uint32_t Mask);
  3652. llvm::Value *EmitX86CpuInit();
  3653. llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
  3654. };
  3655. inline DominatingLLVMValue::saved_type
  3656. DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
  3657. if (!needsSaving(value)) return saved_type(value, false);
  3658. // Otherwise, we need an alloca.
  3659. auto align = CharUnits::fromQuantity(
  3660. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  3661. Address alloca =
  3662. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  3663. CGF.Builder.CreateStore(value, alloca);
  3664. return saved_type(alloca.getPointer(), true);
  3665. }
  3666. inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
  3667. saved_type value) {
  3668. // If the value says it wasn't saved, trust that it's still dominating.
  3669. if (!value.getInt()) return value.getPointer();
  3670. // Otherwise, it should be an alloca instruction, as set up in save().
  3671. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  3672. return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
  3673. }
  3674. } // end namespace CodeGen
  3675. } // end namespace clang
  3676. #endif