CodeGenFunction.h 174 KB

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