CodeGenFunction.h 147 KB

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