CodeGenFunction.h 168 KB

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