CodeGenFunction.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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 coordinates the per-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGBlocks.h"
  15. #include "CGCleanup.h"
  16. #include "CGCUDARuntime.h"
  17. #include "CGCXXABI.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "CodeGenPGO.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/CodeGen/CGFunctionInfo.h"
  31. #include "clang/Frontend/CodeGenOptions.h"
  32. #include "clang/Sema/SemaDiagnostic.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/MDBuilder.h"
  36. #include "llvm/IR/Operator.h"
  37. using namespace clang;
  38. using namespace CodeGen;
  39. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  40. /// markers.
  41. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  42. const LangOptions &LangOpts) {
  43. if (CGOpts.DisableLifetimeMarkers)
  44. return false;
  45. // Asan uses markers for use-after-scope checks.
  46. if (CGOpts.SanitizeAddressUseAfterScope)
  47. return true;
  48. // Disable lifetime markers in msan builds.
  49. // FIXME: Remove this when msan works with lifetime markers.
  50. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  51. return false;
  52. // For now, only in optimized builds.
  53. return CGOpts.OptimizationLevel != 0;
  54. }
  55. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  56. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  57. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  58. CGBuilderInserterTy(this)),
  59. CurFn(nullptr), ReturnValue(Address::invalid()),
  60. CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
  61. IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
  62. SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
  63. BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
  64. NormalCleanupDest(nullptr), NextCleanupDestIndex(1),
  65. FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
  66. EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
  67. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
  68. PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
  69. CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
  70. NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
  71. CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  72. CXXStructorImplicitParamDecl(nullptr),
  73. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  74. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  75. TerminateHandler(nullptr), TrapBB(nullptr),
  76. ShouldEmitLifetimeMarkers(
  77. shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  78. if (!suppressNewContext)
  79. CGM.getCXXABI().getMangleContext().startNewFunction();
  80. llvm::FastMathFlags FMF;
  81. if (CGM.getLangOpts().FastMath)
  82. FMF.setUnsafeAlgebra();
  83. if (CGM.getLangOpts().FiniteMathOnly) {
  84. FMF.setNoNaNs();
  85. FMF.setNoInfs();
  86. }
  87. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  88. FMF.setNoNaNs();
  89. }
  90. if (CGM.getCodeGenOpts().NoSignedZeros) {
  91. FMF.setNoSignedZeros();
  92. }
  93. if (CGM.getCodeGenOpts().ReciprocalMath) {
  94. FMF.setAllowReciprocal();
  95. }
  96. Builder.setFastMathFlags(FMF);
  97. }
  98. CodeGenFunction::~CodeGenFunction() {
  99. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  100. // If there are any unclaimed block infos, go ahead and destroy them
  101. // now. This can happen if IR-gen gets clever and skips evaluating
  102. // something.
  103. if (FirstBlockInfo)
  104. destroyBlockInfos(FirstBlockInfo);
  105. if (getLangOpts().OpenMP && CurFn)
  106. CGM.getOpenMPRuntime().functionFinished(*this);
  107. }
  108. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  109. AlignmentSource *Source) {
  110. return getNaturalTypeAlignment(T->getPointeeType(), Source,
  111. /*forPointee*/ true);
  112. }
  113. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  114. AlignmentSource *Source,
  115. bool forPointeeType) {
  116. // Honor alignment typedef attributes even on incomplete types.
  117. // We also honor them straight for C++ class types, even as pointees;
  118. // there's an expressivity gap here.
  119. if (auto TT = T->getAs<TypedefType>()) {
  120. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  121. if (Source) *Source = AlignmentSource::AttributedType;
  122. return getContext().toCharUnitsFromBits(Align);
  123. }
  124. }
  125. if (Source) *Source = AlignmentSource::Type;
  126. CharUnits Alignment;
  127. if (T->isIncompleteType()) {
  128. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  129. } else {
  130. // For C++ class pointees, we don't know whether we're pointing at a
  131. // base or a complete object, so we generally need to use the
  132. // non-virtual alignment.
  133. const CXXRecordDecl *RD;
  134. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  135. Alignment = CGM.getClassPointerAlignment(RD);
  136. } else {
  137. Alignment = getContext().getTypeAlignInChars(T);
  138. }
  139. // Cap to the global maximum type alignment unless the alignment
  140. // was somehow explicit on the type.
  141. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  142. if (Alignment.getQuantity() > MaxAlign &&
  143. !getContext().isAlignmentRequired(T))
  144. Alignment = CharUnits::fromQuantity(MaxAlign);
  145. }
  146. }
  147. return Alignment;
  148. }
  149. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  150. AlignmentSource AlignSource;
  151. CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
  152. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
  153. CGM.getTBAAInfo(T));
  154. }
  155. /// Given a value of type T* that may not be to a complete object,
  156. /// construct an l-value with the natural pointee alignment of T.
  157. LValue
  158. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  159. AlignmentSource AlignSource;
  160. CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
  161. return MakeAddrLValue(Address(V, Align), T, AlignSource);
  162. }
  163. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  164. return CGM.getTypes().ConvertTypeForMem(T);
  165. }
  166. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  167. return CGM.getTypes().ConvertType(T);
  168. }
  169. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  170. type = type.getCanonicalType();
  171. while (true) {
  172. switch (type->getTypeClass()) {
  173. #define TYPE(name, parent)
  174. #define ABSTRACT_TYPE(name, parent)
  175. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  176. #define DEPENDENT_TYPE(name, parent) case Type::name:
  177. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  178. #include "clang/AST/TypeNodes.def"
  179. llvm_unreachable("non-canonical or dependent type in IR-generation");
  180. case Type::Auto:
  181. llvm_unreachable("undeduced auto type in IR-generation");
  182. // Various scalar types.
  183. case Type::Builtin:
  184. case Type::Pointer:
  185. case Type::BlockPointer:
  186. case Type::LValueReference:
  187. case Type::RValueReference:
  188. case Type::MemberPointer:
  189. case Type::Vector:
  190. case Type::ExtVector:
  191. case Type::FunctionProto:
  192. case Type::FunctionNoProto:
  193. case Type::Enum:
  194. case Type::ObjCObjectPointer:
  195. case Type::Pipe:
  196. return TEK_Scalar;
  197. // Complexes.
  198. case Type::Complex:
  199. return TEK_Complex;
  200. // Arrays, records, and Objective-C objects.
  201. case Type::ConstantArray:
  202. case Type::IncompleteArray:
  203. case Type::VariableArray:
  204. case Type::Record:
  205. case Type::ObjCObject:
  206. case Type::ObjCInterface:
  207. return TEK_Aggregate;
  208. // We operate on atomic values according to their underlying type.
  209. case Type::Atomic:
  210. type = cast<AtomicType>(type)->getValueType();
  211. continue;
  212. }
  213. llvm_unreachable("unknown type kind!");
  214. }
  215. }
  216. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  217. // For cleanliness, we try to avoid emitting the return block for
  218. // simple cases.
  219. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  220. if (CurBB) {
  221. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  222. // We have a valid insert point, reuse it if it is empty or there are no
  223. // explicit jumps to the return block.
  224. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  225. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  226. delete ReturnBlock.getBlock();
  227. } else
  228. EmitBlock(ReturnBlock.getBlock());
  229. return llvm::DebugLoc();
  230. }
  231. // Otherwise, if the return block is the target of a single direct
  232. // branch then we can just put the code in that block instead. This
  233. // cleans up functions which started with a unified return block.
  234. if (ReturnBlock.getBlock()->hasOneUse()) {
  235. llvm::BranchInst *BI =
  236. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  237. if (BI && BI->isUnconditional() &&
  238. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  239. // Record/return the DebugLoc of the simple 'return' expression to be used
  240. // later by the actual 'ret' instruction.
  241. llvm::DebugLoc Loc = BI->getDebugLoc();
  242. Builder.SetInsertPoint(BI->getParent());
  243. BI->eraseFromParent();
  244. delete ReturnBlock.getBlock();
  245. return Loc;
  246. }
  247. }
  248. // FIXME: We are at an unreachable point, there is no reason to emit the block
  249. // unless it has uses. However, we still need a place to put the debug
  250. // region.end for now.
  251. EmitBlock(ReturnBlock.getBlock());
  252. return llvm::DebugLoc();
  253. }
  254. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  255. if (!BB) return;
  256. if (!BB->use_empty())
  257. return CGF.CurFn->getBasicBlockList().push_back(BB);
  258. delete BB;
  259. }
  260. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  261. assert(BreakContinueStack.empty() &&
  262. "mismatched push/pop in break/continue stack!");
  263. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  264. && NumSimpleReturnExprs == NumReturnExprs
  265. && ReturnBlock.getBlock()->use_empty();
  266. // Usually the return expression is evaluated before the cleanup
  267. // code. If the function contains only a simple return statement,
  268. // such as a constant, the location before the cleanup code becomes
  269. // the last useful breakpoint in the function, because the simple
  270. // return expression will be evaluated after the cleanup code. To be
  271. // safe, set the debug location for cleanup code to the location of
  272. // the return statement. Otherwise the cleanup code should be at the
  273. // end of the function's lexical scope.
  274. //
  275. // If there are multiple branches to the return block, the branch
  276. // instructions will get the location of the return statements and
  277. // all will be fine.
  278. if (CGDebugInfo *DI = getDebugInfo()) {
  279. if (OnlySimpleReturnStmts)
  280. DI->EmitLocation(Builder, LastStopPoint);
  281. else
  282. DI->EmitLocation(Builder, EndLoc);
  283. }
  284. // Pop any cleanups that might have been associated with the
  285. // parameters. Do this in whatever block we're currently in; it's
  286. // important to do this before we enter the return block or return
  287. // edges will be *really* confused.
  288. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  289. bool HasOnlyLifetimeMarkers =
  290. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  291. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  292. if (HasCleanups) {
  293. // Make sure the line table doesn't jump back into the body for
  294. // the ret after it's been at EndLoc.
  295. if (CGDebugInfo *DI = getDebugInfo())
  296. if (OnlySimpleReturnStmts)
  297. DI->EmitLocation(Builder, EndLoc);
  298. PopCleanupBlocks(PrologueCleanupDepth);
  299. }
  300. // Emit function epilog (to return).
  301. llvm::DebugLoc Loc = EmitReturnBlock();
  302. if (ShouldInstrumentFunction())
  303. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  304. // Emit debug descriptor for function end.
  305. if (CGDebugInfo *DI = getDebugInfo())
  306. DI->EmitFunctionEnd(Builder);
  307. // Reset the debug location to that of the simple 'return' expression, if any
  308. // rather than that of the end of the function's scope '}'.
  309. ApplyDebugLocation AL(*this, Loc);
  310. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  311. EmitEndEHSpec(CurCodeDecl);
  312. assert(EHStack.empty() &&
  313. "did not remove all scopes from cleanup stack!");
  314. // If someone did an indirect goto, emit the indirect goto block at the end of
  315. // the function.
  316. if (IndirectBranch) {
  317. EmitBlock(IndirectBranch->getParent());
  318. Builder.ClearInsertionPoint();
  319. }
  320. // If some of our locals escaped, insert a call to llvm.localescape in the
  321. // entry block.
  322. if (!EscapedLocals.empty()) {
  323. // Invert the map from local to index into a simple vector. There should be
  324. // no holes.
  325. SmallVector<llvm::Value *, 4> EscapeArgs;
  326. EscapeArgs.resize(EscapedLocals.size());
  327. for (auto &Pair : EscapedLocals)
  328. EscapeArgs[Pair.second] = Pair.first;
  329. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  330. &CGM.getModule(), llvm::Intrinsic::localescape);
  331. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  332. }
  333. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  334. llvm::Instruction *Ptr = AllocaInsertPt;
  335. AllocaInsertPt = nullptr;
  336. Ptr->eraseFromParent();
  337. // If someone took the address of a label but never did an indirect goto, we
  338. // made a zero entry PHI node, which is illegal, zap it now.
  339. if (IndirectBranch) {
  340. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  341. if (PN->getNumIncomingValues() == 0) {
  342. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  343. PN->eraseFromParent();
  344. }
  345. }
  346. EmitIfUsed(*this, EHResumeBlock);
  347. EmitIfUsed(*this, TerminateLandingPad);
  348. EmitIfUsed(*this, TerminateHandler);
  349. EmitIfUsed(*this, UnreachableBlock);
  350. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  351. EmitDeclMetadata();
  352. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  353. I = DeferredReplacements.begin(),
  354. E = DeferredReplacements.end();
  355. I != E; ++I) {
  356. I->first->replaceAllUsesWith(I->second);
  357. I->first->eraseFromParent();
  358. }
  359. }
  360. /// ShouldInstrumentFunction - Return true if the current function should be
  361. /// instrumented with __cyg_profile_func_* calls
  362. bool CodeGenFunction::ShouldInstrumentFunction() {
  363. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  364. return false;
  365. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  366. return false;
  367. return true;
  368. }
  369. /// ShouldXRayInstrument - Return true if the current function should be
  370. /// instrumented with XRay nop sleds.
  371. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  372. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  373. }
  374. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  375. /// instrumentation function with the current function and the call site, if
  376. /// function instrumentation is enabled.
  377. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  378. auto NL = ApplyDebugLocation::CreateArtificial(*this);
  379. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  380. llvm::PointerType *PointerTy = Int8PtrTy;
  381. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  382. llvm::FunctionType *FunctionTy =
  383. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  384. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  385. llvm::CallInst *CallSite = Builder.CreateCall(
  386. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  387. llvm::ConstantInt::get(Int32Ty, 0),
  388. "callsite");
  389. llvm::Value *args[] = {
  390. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  391. CallSite
  392. };
  393. EmitNounwindRuntimeCall(F, args);
  394. }
  395. static void removeImageAccessQualifier(std::string& TyName) {
  396. std::string ReadOnlyQual("__read_only");
  397. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  398. if (ReadOnlyPos != std::string::npos)
  399. // "+ 1" for the space after access qualifier.
  400. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  401. else {
  402. std::string WriteOnlyQual("__write_only");
  403. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  404. if (WriteOnlyPos != std::string::npos)
  405. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  406. else {
  407. std::string ReadWriteQual("__read_write");
  408. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  409. if (ReadWritePos != std::string::npos)
  410. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  411. }
  412. }
  413. }
  414. // Returns the address space id that should be produced to the
  415. // kernel_arg_addr_space metadata. This is always fixed to the ids
  416. // as specified in the SPIR 2.0 specification in order to differentiate
  417. // for example in clGetKernelArgInfo() implementation between the address
  418. // spaces with targets without unique mapping to the OpenCL address spaces
  419. // (basically all single AS CPUs).
  420. static unsigned ArgInfoAddressSpace(unsigned LangAS) {
  421. switch (LangAS) {
  422. case LangAS::opencl_global: return 1;
  423. case LangAS::opencl_constant: return 2;
  424. case LangAS::opencl_local: return 3;
  425. case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
  426. default:
  427. return 0; // Assume private.
  428. }
  429. }
  430. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  431. // information in the program executable. The argument information stored
  432. // includes the argument name, its type, the address and access qualifiers used.
  433. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  434. CodeGenModule &CGM, llvm::LLVMContext &Context,
  435. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  436. // Create MDNodes that represent the kernel arg metadata.
  437. // Each MDNode is a list in the form of "key", N number of values which is
  438. // the same number of values as their are kernel arguments.
  439. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  440. // MDNode for the kernel argument address space qualifiers.
  441. SmallVector<llvm::Metadata *, 8> addressQuals;
  442. // MDNode for the kernel argument access qualifiers (images only).
  443. SmallVector<llvm::Metadata *, 8> accessQuals;
  444. // MDNode for the kernel argument type names.
  445. SmallVector<llvm::Metadata *, 8> argTypeNames;
  446. // MDNode for the kernel argument base type names.
  447. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  448. // MDNode for the kernel argument type qualifiers.
  449. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  450. // MDNode for the kernel argument names.
  451. SmallVector<llvm::Metadata *, 8> argNames;
  452. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  453. const ParmVarDecl *parm = FD->getParamDecl(i);
  454. QualType ty = parm->getType();
  455. std::string typeQuals;
  456. if (ty->isPointerType()) {
  457. QualType pointeeTy = ty->getPointeeType();
  458. // Get address qualifier.
  459. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  460. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  461. // Get argument type name.
  462. std::string typeName =
  463. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  464. // Turn "unsigned type" to "utype"
  465. std::string::size_type pos = typeName.find("unsigned");
  466. if (pointeeTy.isCanonical() && pos != std::string::npos)
  467. typeName.erase(pos+1, 8);
  468. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  469. std::string baseTypeName =
  470. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  471. Policy) +
  472. "*";
  473. // Turn "unsigned type" to "utype"
  474. pos = baseTypeName.find("unsigned");
  475. if (pos != std::string::npos)
  476. baseTypeName.erase(pos+1, 8);
  477. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  478. // Get argument type qualifiers:
  479. if (ty.isRestrictQualified())
  480. typeQuals = "restrict";
  481. if (pointeeTy.isConstQualified() ||
  482. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  483. typeQuals += typeQuals.empty() ? "const" : " const";
  484. if (pointeeTy.isVolatileQualified())
  485. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  486. } else {
  487. uint32_t AddrSpc = 0;
  488. bool isPipe = ty->isPipeType();
  489. if (ty->isImageType() || isPipe)
  490. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  491. addressQuals.push_back(
  492. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  493. // Get argument type name.
  494. std::string typeName;
  495. if (isPipe)
  496. typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
  497. .getAsString(Policy);
  498. else
  499. typeName = ty.getUnqualifiedType().getAsString(Policy);
  500. // Turn "unsigned type" to "utype"
  501. std::string::size_type pos = typeName.find("unsigned");
  502. if (ty.isCanonical() && pos != std::string::npos)
  503. typeName.erase(pos+1, 8);
  504. std::string baseTypeName;
  505. if (isPipe)
  506. baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
  507. ->getElementType().getCanonicalType()
  508. .getAsString(Policy);
  509. else
  510. baseTypeName =
  511. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  512. // Remove access qualifiers on images
  513. // (as they are inseparable from type in clang implementation,
  514. // but OpenCL spec provides a special query to get access qualifier
  515. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  516. if (ty->isImageType()) {
  517. removeImageAccessQualifier(typeName);
  518. removeImageAccessQualifier(baseTypeName);
  519. }
  520. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  521. // Turn "unsigned type" to "utype"
  522. pos = baseTypeName.find("unsigned");
  523. if (pos != std::string::npos)
  524. baseTypeName.erase(pos+1, 8);
  525. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  526. // Get argument type qualifiers:
  527. if (ty.isConstQualified())
  528. typeQuals = "const";
  529. if (ty.isVolatileQualified())
  530. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  531. if (isPipe)
  532. typeQuals = "pipe";
  533. }
  534. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  535. // Get image and pipe access qualifier:
  536. if (ty->isImageType()|| ty->isPipeType()) {
  537. const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>();
  538. if (A && A->isWriteOnly())
  539. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  540. else if (A && A->isReadWrite())
  541. accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
  542. else
  543. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  544. } else
  545. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  546. // Get argument name.
  547. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  548. }
  549. Fn->setMetadata("kernel_arg_addr_space",
  550. llvm::MDNode::get(Context, addressQuals));
  551. Fn->setMetadata("kernel_arg_access_qual",
  552. llvm::MDNode::get(Context, accessQuals));
  553. Fn->setMetadata("kernel_arg_type",
  554. llvm::MDNode::get(Context, argTypeNames));
  555. Fn->setMetadata("kernel_arg_base_type",
  556. llvm::MDNode::get(Context, argBaseTypeNames));
  557. Fn->setMetadata("kernel_arg_type_qual",
  558. llvm::MDNode::get(Context, argTypeQuals));
  559. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  560. Fn->setMetadata("kernel_arg_name",
  561. llvm::MDNode::get(Context, argNames));
  562. }
  563. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  564. llvm::Function *Fn)
  565. {
  566. if (!FD->hasAttr<OpenCLKernelAttr>())
  567. return;
  568. llvm::LLVMContext &Context = getLLVMContext();
  569. GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
  570. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  571. QualType hintQTy = A->getTypeHint();
  572. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  573. bool isSignedInteger =
  574. hintQTy->isSignedIntegerType() ||
  575. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  576. llvm::Metadata *attrMDArgs[] = {
  577. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  578. CGM.getTypes().ConvertType(A->getTypeHint()))),
  579. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  580. llvm::IntegerType::get(Context, 32),
  581. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
  582. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs));
  583. }
  584. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  585. llvm::Metadata *attrMDArgs[] = {
  586. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  587. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  588. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  589. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs));
  590. }
  591. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  592. llvm::Metadata *attrMDArgs[] = {
  593. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  594. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  595. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  596. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs));
  597. }
  598. }
  599. /// Determine whether the function F ends with a return stmt.
  600. static bool endsWithReturn(const Decl* F) {
  601. const Stmt *Body = nullptr;
  602. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  603. Body = FD->getBody();
  604. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  605. Body = OMD->getBody();
  606. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  607. auto LastStmt = CS->body_rbegin();
  608. if (LastStmt != CS->body_rend())
  609. return isa<ReturnStmt>(*LastStmt);
  610. }
  611. return false;
  612. }
  613. static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  614. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  615. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  616. }
  617. void CodeGenFunction::StartFunction(GlobalDecl GD,
  618. QualType RetTy,
  619. llvm::Function *Fn,
  620. const CGFunctionInfo &FnInfo,
  621. const FunctionArgList &Args,
  622. SourceLocation Loc,
  623. SourceLocation StartLoc) {
  624. assert(!CurFn &&
  625. "Do not use a CodeGenFunction object for more than one function");
  626. const Decl *D = GD.getDecl();
  627. DidCallStackSave = false;
  628. CurCodeDecl = D;
  629. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  630. if (FD->usesSEHTry())
  631. CurSEHParent = FD;
  632. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  633. FnRetTy = RetTy;
  634. CurFn = Fn;
  635. CurFnInfo = &FnInfo;
  636. assert(CurFn->isDeclaration() && "Function already has body?");
  637. if (CGM.isInSanitizerBlacklist(Fn, Loc))
  638. SanOpts.clear();
  639. if (D) {
  640. // Apply the no_sanitize* attributes to SanOpts.
  641. for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
  642. SanOpts.Mask &= ~Attr->getMask();
  643. }
  644. // Apply sanitizer attributes to the function.
  645. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  646. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  647. if (SanOpts.has(SanitizerKind::Thread))
  648. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  649. if (SanOpts.has(SanitizerKind::Memory))
  650. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  651. if (SanOpts.has(SanitizerKind::SafeStack))
  652. Fn->addFnAttr(llvm::Attribute::SafeStack);
  653. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  654. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  655. if (SanOpts.has(SanitizerKind::Thread)) {
  656. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  657. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  658. if (OMD->getMethodFamily() == OMF_dealloc ||
  659. OMD->getMethodFamily() == OMF_initialize ||
  660. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  661. markAsIgnoreThreadCheckingAtRuntime(Fn);
  662. }
  663. } else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  664. IdentifierInfo *II = FD->getIdentifier();
  665. if (II && II->isStr("__destroy_helper_block_"))
  666. markAsIgnoreThreadCheckingAtRuntime(Fn);
  667. }
  668. }
  669. // Apply xray attributes to the function (as a string, for now)
  670. if (D && ShouldXRayInstrumentFunction()) {
  671. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  672. if (XRayAttr->alwaysXRayInstrument())
  673. Fn->addFnAttr("function-instrument", "xray-always");
  674. if (XRayAttr->neverXRayInstrument())
  675. Fn->addFnAttr("function-instrument", "xray-never");
  676. } else {
  677. Fn->addFnAttr(
  678. "xray-instruction-threshold",
  679. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  680. }
  681. }
  682. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  683. if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  684. CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn);
  685. // Add no-jump-tables value.
  686. Fn->addFnAttr("no-jump-tables",
  687. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  688. if (getLangOpts().OpenCL) {
  689. // Add metadata for a kernel function.
  690. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  691. EmitOpenCLKernelMetadata(FD, Fn);
  692. }
  693. // If we are checking function types, emit a function type signature as
  694. // prologue data.
  695. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  696. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  697. if (llvm::Constant *PrologueSig =
  698. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  699. llvm::Constant *FTRTTIConst =
  700. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  701. llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
  702. llvm::Constant *PrologueStructConst =
  703. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  704. Fn->setPrologueData(PrologueStructConst);
  705. }
  706. }
  707. }
  708. // If we're in C++ mode and the function name is "main", it is guaranteed
  709. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  710. // used within a program").
  711. if (getLangOpts().CPlusPlus)
  712. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  713. if (FD->isMain())
  714. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  715. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  716. // Create a marker to make it easy to insert allocas into the entryblock
  717. // later. Don't create this with the builder, because we don't want it
  718. // folded.
  719. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  720. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  721. ReturnBlock = getJumpDestInCurrentScope("return");
  722. Builder.SetInsertPoint(EntryBB);
  723. // Emit subprogram debug descriptor.
  724. if (CGDebugInfo *DI = getDebugInfo()) {
  725. // Reconstruct the type from the argument list so that implicit parameters,
  726. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  727. // convention.
  728. CallingConv CC = CallingConv::CC_C;
  729. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  730. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  731. CC = SrcFnTy->getCallConv();
  732. SmallVector<QualType, 16> ArgTypes;
  733. for (const VarDecl *VD : Args)
  734. ArgTypes.push_back(VD->getType());
  735. QualType FnType = getContext().getFunctionType(
  736. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  737. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  738. }
  739. if (ShouldInstrumentFunction())
  740. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  741. // Since emitting the mcount call here impacts optimizations such as function
  742. // inlining, we just add an attribute to insert a mcount call in backend.
  743. // The attribute "counting-function" is set to mcount function name which is
  744. // architecture dependent.
  745. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  746. Fn->addFnAttr("counting-function", getTarget().getMCountName());
  747. if (RetTy->isVoidType()) {
  748. // Void type; nothing to return.
  749. ReturnValue = Address::invalid();
  750. // Count the implicit return.
  751. if (!endsWithReturn(D))
  752. ++NumReturnExprs;
  753. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  754. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  755. // Indirect aggregate return; emit returned value directly into sret slot.
  756. // This reduces code size, and affects correctness in C++.
  757. auto AI = CurFn->arg_begin();
  758. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  759. ++AI;
  760. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  761. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  762. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  763. // Load the sret pointer from the argument struct and return into that.
  764. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  765. llvm::Function::arg_iterator EI = CurFn->arg_end();
  766. --EI;
  767. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  768. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  769. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  770. } else {
  771. ReturnValue = CreateIRTemp(RetTy, "retval");
  772. // Tell the epilog emitter to autorelease the result. We do this
  773. // now so that various specialized functions can suppress it
  774. // during their IR-generation.
  775. if (getLangOpts().ObjCAutoRefCount &&
  776. !CurFnInfo->isReturnsRetained() &&
  777. RetTy->isObjCRetainableType())
  778. AutoreleaseResult = true;
  779. }
  780. EmitStartEHSpec(CurCodeDecl);
  781. PrologueCleanupDepth = EHStack.stable_begin();
  782. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  783. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  784. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  785. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  786. if (MD->getParent()->isLambda() &&
  787. MD->getOverloadedOperator() == OO_Call) {
  788. // We're in a lambda; figure out the captures.
  789. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  790. LambdaThisCaptureField);
  791. if (LambdaThisCaptureField) {
  792. // If the lambda captures the object referred to by '*this' - either by
  793. // value or by reference, make sure CXXThisValue points to the correct
  794. // object.
  795. // Get the lvalue for the field (which is a copy of the enclosing object
  796. // or contains the address of the enclosing object).
  797. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  798. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  799. // If the enclosing object was captured by value, just use its address.
  800. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  801. } else {
  802. // Load the lvalue pointed to by the field, since '*this' was captured
  803. // by reference.
  804. CXXThisValue =
  805. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  806. }
  807. }
  808. for (auto *FD : MD->getParent()->fields()) {
  809. if (FD->hasCapturedVLAType()) {
  810. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  811. SourceLocation()).getScalarVal();
  812. auto VAT = FD->getCapturedVLAType();
  813. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  814. }
  815. }
  816. } else {
  817. // Not in a lambda; just use 'this' from the method.
  818. // FIXME: Should we generate a new load for each use of 'this'? The
  819. // fast register allocator would be happier...
  820. CXXThisValue = CXXABIThisValue;
  821. }
  822. }
  823. // If any of the arguments have a variably modified type, make sure to
  824. // emit the type size.
  825. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  826. i != e; ++i) {
  827. const VarDecl *VD = *i;
  828. // Dig out the type as written from ParmVarDecls; it's unclear whether
  829. // the standard (C99 6.9.1p10) requires this, but we're following the
  830. // precedent set by gcc.
  831. QualType Ty;
  832. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  833. Ty = PVD->getOriginalType();
  834. else
  835. Ty = VD->getType();
  836. if (Ty->isVariablyModifiedType())
  837. EmitVariablyModifiedType(Ty);
  838. }
  839. // Emit a location at the end of the prologue.
  840. if (CGDebugInfo *DI = getDebugInfo())
  841. DI->EmitLocation(Builder, StartLoc);
  842. }
  843. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  844. const Stmt *Body) {
  845. incrementProfileCounter(Body);
  846. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  847. EmitCompoundStmtWithoutScope(*S);
  848. else
  849. EmitStmt(Body);
  850. }
  851. /// When instrumenting to collect profile data, the counts for some blocks
  852. /// such as switch cases need to not include the fall-through counts, so
  853. /// emit a branch around the instrumentation code. When not instrumenting,
  854. /// this just calls EmitBlock().
  855. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  856. const Stmt *S) {
  857. llvm::BasicBlock *SkipCountBB = nullptr;
  858. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  859. // When instrumenting for profiling, the fallthrough to certain
  860. // statements needs to skip over the instrumentation code so that we
  861. // get an accurate count.
  862. SkipCountBB = createBasicBlock("skipcount");
  863. EmitBranch(SkipCountBB);
  864. }
  865. EmitBlock(BB);
  866. uint64_t CurrentCount = getCurrentProfileCount();
  867. incrementProfileCounter(S);
  868. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  869. if (SkipCountBB)
  870. EmitBlock(SkipCountBB);
  871. }
  872. /// Tries to mark the given function nounwind based on the
  873. /// non-existence of any throwing calls within it. We believe this is
  874. /// lightweight enough to do at -O0.
  875. static void TryMarkNoThrow(llvm::Function *F) {
  876. // LLVM treats 'nounwind' on a function as part of the type, so we
  877. // can't do this on functions that can be overwritten.
  878. if (F->isInterposable()) return;
  879. for (llvm::BasicBlock &BB : *F)
  880. for (llvm::Instruction &I : BB)
  881. if (I.mayThrow())
  882. return;
  883. F->setDoesNotThrow();
  884. }
  885. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  886. FunctionArgList &Args) {
  887. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  888. QualType ResTy = FD->getReturnType();
  889. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  890. if (MD && MD->isInstance()) {
  891. if (CGM.getCXXABI().HasThisReturn(GD))
  892. ResTy = MD->getThisType(getContext());
  893. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  894. ResTy = CGM.getContext().VoidPtrTy;
  895. CGM.getCXXABI().buildThisParam(*this, Args);
  896. }
  897. // The base version of an inheriting constructor whose constructed base is a
  898. // virtual base is not passed any arguments (because it doesn't actually call
  899. // the inherited constructor).
  900. bool PassedParams = true;
  901. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  902. if (auto Inherited = CD->getInheritedConstructor())
  903. PassedParams =
  904. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  905. if (PassedParams) {
  906. for (auto *Param : FD->parameters()) {
  907. Args.push_back(Param);
  908. if (!Param->hasAttr<PassObjectSizeAttr>())
  909. continue;
  910. IdentifierInfo *NoID = nullptr;
  911. auto *Implicit = ImplicitParamDecl::Create(
  912. getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
  913. getContext().getSizeType());
  914. SizeArguments[Param] = Implicit;
  915. Args.push_back(Implicit);
  916. }
  917. }
  918. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  919. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  920. return ResTy;
  921. }
  922. static bool
  923. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  924. const ASTContext &Context) {
  925. QualType T = FD->getReturnType();
  926. // Avoid the optimization for functions that return a record type with a
  927. // trivial destructor or another trivially copyable type.
  928. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  929. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  930. return !ClassDecl->hasTrivialDestructor();
  931. }
  932. return !T.isTriviallyCopyableType(Context);
  933. }
  934. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  935. const CGFunctionInfo &FnInfo) {
  936. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  937. CurGD = GD;
  938. FunctionArgList Args;
  939. QualType ResTy = BuildFunctionArgList(GD, Args);
  940. // Check if we should generate debug info for this function.
  941. if (FD->hasAttr<NoDebugAttr>())
  942. DebugInfo = nullptr; // disable debug info indefinitely for this function
  943. SourceRange BodyRange;
  944. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  945. CurEHLocation = BodyRange.getEnd();
  946. // Use the location of the start of the function to determine where
  947. // the function definition is located. By default use the location
  948. // of the declaration as the location for the subprogram. A function
  949. // may lack a declaration in the source code if it is created by code
  950. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  951. SourceLocation Loc = FD->getLocation();
  952. // If this is a function specialization then use the pattern body
  953. // as the location for the function.
  954. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  955. if (SpecDecl->hasBody(SpecDecl))
  956. Loc = SpecDecl->getLocation();
  957. Stmt *Body = FD->getBody();
  958. // Initialize helper which will detect jumps which can cause invalid lifetime
  959. // markers.
  960. if (Body && ShouldEmitLifetimeMarkers)
  961. Bypasses.Init(Body);
  962. // Emit the standard function prologue.
  963. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  964. // Generate the body of the function.
  965. PGO.assignRegionCounters(GD, CurFn);
  966. if (isa<CXXDestructorDecl>(FD))
  967. EmitDestructorBody(Args);
  968. else if (isa<CXXConstructorDecl>(FD))
  969. EmitConstructorBody(Args);
  970. else if (getLangOpts().CUDA &&
  971. !getLangOpts().CUDAIsDevice &&
  972. FD->hasAttr<CUDAGlobalAttr>())
  973. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  974. else if (isa<CXXConversionDecl>(FD) &&
  975. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  976. // The lambda conversion to block pointer is special; the semantics can't be
  977. // expressed in the AST, so IRGen needs to special-case it.
  978. EmitLambdaToBlockPointerBody(Args);
  979. } else if (isa<CXXMethodDecl>(FD) &&
  980. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  981. // The lambda static invoker function is special, because it forwards or
  982. // clones the body of the function call operator (but is actually static).
  983. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  984. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  985. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  986. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  987. // Implicit copy-assignment gets the same special treatment as implicit
  988. // copy-constructors.
  989. emitImplicitAssignmentOperatorBody(Args);
  990. } else if (Body) {
  991. EmitFunctionBody(Args, Body);
  992. } else
  993. llvm_unreachable("no definition for emitted function");
  994. // C++11 [stmt.return]p2:
  995. // Flowing off the end of a function [...] results in undefined behavior in
  996. // a value-returning function.
  997. // C11 6.9.1p12:
  998. // If the '}' that terminates a function is reached, and the value of the
  999. // function call is used by the caller, the behavior is undefined.
  1000. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1001. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1002. bool ShouldEmitUnreachable =
  1003. CGM.getCodeGenOpts().StrictReturn ||
  1004. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1005. if (SanOpts.has(SanitizerKind::Return)) {
  1006. SanitizerScope SanScope(this);
  1007. llvm::Value *IsFalse = Builder.getFalse();
  1008. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1009. SanitizerHandler::MissingReturn,
  1010. EmitCheckSourceLocation(FD->getLocation()), None);
  1011. } else if (ShouldEmitUnreachable) {
  1012. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1013. EmitTrapCall(llvm::Intrinsic::trap);
  1014. }
  1015. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1016. Builder.CreateUnreachable();
  1017. Builder.ClearInsertionPoint();
  1018. }
  1019. }
  1020. // Emit the standard function epilogue.
  1021. FinishFunction(BodyRange.getEnd());
  1022. // If we haven't marked the function nothrow through other means, do
  1023. // a quick pass now to see if we can.
  1024. if (!CurFn->doesNotThrow())
  1025. TryMarkNoThrow(CurFn);
  1026. }
  1027. /// ContainsLabel - Return true if the statement contains a label in it. If
  1028. /// this statement is not executed normally, it not containing a label means
  1029. /// that we can just remove the code.
  1030. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1031. // Null statement, not a label!
  1032. if (!S) return false;
  1033. // If this is a label, we have to emit the code, consider something like:
  1034. // if (0) { ... foo: bar(); } goto foo;
  1035. //
  1036. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1037. // can't jump to one from outside their declared region.
  1038. if (isa<LabelStmt>(S))
  1039. return true;
  1040. // If this is a case/default statement, and we haven't seen a switch, we have
  1041. // to emit the code.
  1042. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1043. return true;
  1044. // If this is a switch statement, we want to ignore cases below it.
  1045. if (isa<SwitchStmt>(S))
  1046. IgnoreCaseStmts = true;
  1047. // Scan subexpressions for verboten labels.
  1048. for (const Stmt *SubStmt : S->children())
  1049. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1050. return true;
  1051. return false;
  1052. }
  1053. /// containsBreak - Return true if the statement contains a break out of it.
  1054. /// If the statement (recursively) contains a switch or loop with a break
  1055. /// inside of it, this is fine.
  1056. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1057. // Null statement, not a label!
  1058. if (!S) return false;
  1059. // If this is a switch or loop that defines its own break scope, then we can
  1060. // include it and anything inside of it.
  1061. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1062. isa<ForStmt>(S))
  1063. return false;
  1064. if (isa<BreakStmt>(S))
  1065. return true;
  1066. // Scan subexpressions for verboten breaks.
  1067. for (const Stmt *SubStmt : S->children())
  1068. if (containsBreak(SubStmt))
  1069. return true;
  1070. return false;
  1071. }
  1072. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1073. if (!S) return false;
  1074. // Some statement kinds add a scope and thus never add a decl to the current
  1075. // scope. Note, this list is longer than the list of statements that might
  1076. // have an unscoped decl nested within them, but this way is conservatively
  1077. // correct even if more statement kinds are added.
  1078. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1079. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1080. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1081. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1082. return false;
  1083. if (isa<DeclStmt>(S))
  1084. return true;
  1085. for (const Stmt *SubStmt : S->children())
  1086. if (mightAddDeclToScope(SubStmt))
  1087. return true;
  1088. return false;
  1089. }
  1090. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1091. /// to a constant, or if it does but contains a label, return false. If it
  1092. /// constant folds return true and set the boolean result in Result.
  1093. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1094. bool &ResultBool,
  1095. bool AllowLabels) {
  1096. llvm::APSInt ResultInt;
  1097. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1098. return false;
  1099. ResultBool = ResultInt.getBoolValue();
  1100. return true;
  1101. }
  1102. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1103. /// to a constant, or if it does but contains a label, return false. If it
  1104. /// constant folds return true and set the folded value.
  1105. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1106. llvm::APSInt &ResultInt,
  1107. bool AllowLabels) {
  1108. // FIXME: Rename and handle conversion of other evaluatable things
  1109. // to bool.
  1110. llvm::APSInt Int;
  1111. if (!Cond->EvaluateAsInt(Int, getContext()))
  1112. return false; // Not foldable, not integer or not fully evaluatable.
  1113. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1114. return false; // Contains a label.
  1115. ResultInt = Int;
  1116. return true;
  1117. }
  1118. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1119. /// statement) to the specified blocks. Based on the condition, this might try
  1120. /// to simplify the codegen of the conditional based on the branch.
  1121. ///
  1122. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1123. llvm::BasicBlock *TrueBlock,
  1124. llvm::BasicBlock *FalseBlock,
  1125. uint64_t TrueCount) {
  1126. Cond = Cond->IgnoreParens();
  1127. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1128. // Handle X && Y in a condition.
  1129. if (CondBOp->getOpcode() == BO_LAnd) {
  1130. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1131. // folded if the case was simple enough.
  1132. bool ConstantBool = false;
  1133. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1134. ConstantBool) {
  1135. // br(1 && X) -> br(X).
  1136. incrementProfileCounter(CondBOp);
  1137. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1138. TrueCount);
  1139. }
  1140. // If we have "X && 1", simplify the code to use an uncond branch.
  1141. // "X && 0" would have been constant folded to 0.
  1142. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1143. ConstantBool) {
  1144. // br(X && 1) -> br(X).
  1145. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1146. TrueCount);
  1147. }
  1148. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1149. // want to jump to the FalseBlock.
  1150. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1151. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1152. // can be propagated to that branch.
  1153. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1154. ConditionalEvaluation eval(*this);
  1155. {
  1156. ApplyDebugLocation DL(*this, Cond);
  1157. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1158. EmitBlock(LHSTrue);
  1159. }
  1160. incrementProfileCounter(CondBOp);
  1161. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1162. // Any temporaries created here are conditional.
  1163. eval.begin(*this);
  1164. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1165. eval.end(*this);
  1166. return;
  1167. }
  1168. if (CondBOp->getOpcode() == BO_LOr) {
  1169. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1170. // folded if the case was simple enough.
  1171. bool ConstantBool = false;
  1172. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1173. !ConstantBool) {
  1174. // br(0 || X) -> br(X).
  1175. incrementProfileCounter(CondBOp);
  1176. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1177. TrueCount);
  1178. }
  1179. // If we have "X || 0", simplify the code to use an uncond branch.
  1180. // "X || 1" would have been constant folded to 1.
  1181. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1182. !ConstantBool) {
  1183. // br(X || 0) -> br(X).
  1184. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1185. TrueCount);
  1186. }
  1187. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1188. // want to jump to the TrueBlock.
  1189. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1190. // We have the count for entry to the RHS and for the whole expression
  1191. // being true, so we can divy up True count between the short circuit and
  1192. // the RHS.
  1193. uint64_t LHSCount =
  1194. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1195. uint64_t RHSCount = TrueCount - LHSCount;
  1196. ConditionalEvaluation eval(*this);
  1197. {
  1198. ApplyDebugLocation DL(*this, Cond);
  1199. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1200. EmitBlock(LHSFalse);
  1201. }
  1202. incrementProfileCounter(CondBOp);
  1203. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1204. // Any temporaries created here are conditional.
  1205. eval.begin(*this);
  1206. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1207. eval.end(*this);
  1208. return;
  1209. }
  1210. }
  1211. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1212. // br(!x, t, f) -> br(x, f, t)
  1213. if (CondUOp->getOpcode() == UO_LNot) {
  1214. // Negate the count.
  1215. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1216. // Negate the condition and swap the destination blocks.
  1217. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1218. FalseCount);
  1219. }
  1220. }
  1221. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1222. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1223. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1224. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1225. ConditionalEvaluation cond(*this);
  1226. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1227. getProfileCount(CondOp));
  1228. // When computing PGO branch weights, we only know the overall count for
  1229. // the true block. This code is essentially doing tail duplication of the
  1230. // naive code-gen, introducing new edges for which counts are not
  1231. // available. Divide the counts proportionally between the LHS and RHS of
  1232. // the conditional operator.
  1233. uint64_t LHSScaledTrueCount = 0;
  1234. if (TrueCount) {
  1235. double LHSRatio =
  1236. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1237. LHSScaledTrueCount = TrueCount * LHSRatio;
  1238. }
  1239. cond.begin(*this);
  1240. EmitBlock(LHSBlock);
  1241. incrementProfileCounter(CondOp);
  1242. {
  1243. ApplyDebugLocation DL(*this, Cond);
  1244. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1245. LHSScaledTrueCount);
  1246. }
  1247. cond.end(*this);
  1248. cond.begin(*this);
  1249. EmitBlock(RHSBlock);
  1250. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1251. TrueCount - LHSScaledTrueCount);
  1252. cond.end(*this);
  1253. return;
  1254. }
  1255. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1256. // Conditional operator handling can give us a throw expression as a
  1257. // condition for a case like:
  1258. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1259. // Fold this to:
  1260. // br(c, throw x, br(y, t, f))
  1261. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1262. return;
  1263. }
  1264. // If the branch has a condition wrapped by __builtin_unpredictable,
  1265. // create metadata that specifies that the branch is unpredictable.
  1266. // Don't bother if not optimizing because that metadata would not be used.
  1267. llvm::MDNode *Unpredictable = nullptr;
  1268. auto *Call = dyn_cast<CallExpr>(Cond);
  1269. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1270. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1271. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1272. llvm::MDBuilder MDHelper(getLLVMContext());
  1273. Unpredictable = MDHelper.createUnpredictable();
  1274. }
  1275. }
  1276. // Create branch weights based on the number of times we get here and the
  1277. // number of times the condition should be true.
  1278. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1279. llvm::MDNode *Weights =
  1280. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1281. // Emit the code with the fully general case.
  1282. llvm::Value *CondV;
  1283. {
  1284. ApplyDebugLocation DL(*this, Cond);
  1285. CondV = EvaluateExprAsBool(Cond);
  1286. }
  1287. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1288. }
  1289. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1290. /// specified stmt yet.
  1291. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1292. CGM.ErrorUnsupported(S, Type);
  1293. }
  1294. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1295. /// variable-length array whose elements have a non-zero bit-pattern.
  1296. ///
  1297. /// \param baseType the inner-most element type of the array
  1298. /// \param src - a char* pointing to the bit-pattern for a single
  1299. /// base element of the array
  1300. /// \param sizeInChars - the total size of the VLA, in chars
  1301. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1302. Address dest, Address src,
  1303. llvm::Value *sizeInChars) {
  1304. CGBuilderTy &Builder = CGF.Builder;
  1305. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1306. llvm::Value *baseSizeInChars
  1307. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1308. Address begin =
  1309. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1310. llvm::Value *end =
  1311. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1312. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1313. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1314. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1315. // Make a loop over the VLA. C99 guarantees that the VLA element
  1316. // count must be nonzero.
  1317. CGF.EmitBlock(loopBB);
  1318. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1319. cur->addIncoming(begin.getPointer(), originBB);
  1320. CharUnits curAlign =
  1321. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1322. // memcpy the individual element bit-pattern.
  1323. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1324. /*volatile*/ false);
  1325. // Go to the next element.
  1326. llvm::Value *next =
  1327. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1328. // Leave if that's the end of the VLA.
  1329. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1330. Builder.CreateCondBr(done, contBB, loopBB);
  1331. cur->addIncoming(next, loopBB);
  1332. CGF.EmitBlock(contBB);
  1333. }
  1334. void
  1335. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1336. // Ignore empty classes in C++.
  1337. if (getLangOpts().CPlusPlus) {
  1338. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1339. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1340. return;
  1341. }
  1342. }
  1343. // Cast the dest ptr to the appropriate i8 pointer type.
  1344. if (DestPtr.getElementType() != Int8Ty)
  1345. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1346. // Get size and alignment info for this aggregate.
  1347. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1348. llvm::Value *SizeVal;
  1349. const VariableArrayType *vla;
  1350. // Don't bother emitting a zero-byte memset.
  1351. if (size.isZero()) {
  1352. // But note that getTypeInfo returns 0 for a VLA.
  1353. if (const VariableArrayType *vlaType =
  1354. dyn_cast_or_null<VariableArrayType>(
  1355. getContext().getAsArrayType(Ty))) {
  1356. QualType eltType;
  1357. llvm::Value *numElts;
  1358. std::tie(numElts, eltType) = getVLASize(vlaType);
  1359. SizeVal = numElts;
  1360. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1361. if (!eltSize.isOne())
  1362. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1363. vla = vlaType;
  1364. } else {
  1365. return;
  1366. }
  1367. } else {
  1368. SizeVal = CGM.getSize(size);
  1369. vla = nullptr;
  1370. }
  1371. // If the type contains a pointer to data member we can't memset it to zero.
  1372. // Instead, create a null constant and copy it to the destination.
  1373. // TODO: there are other patterns besides zero that we can usefully memset,
  1374. // like -1, which happens to be the pattern used by member-pointers.
  1375. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1376. // For a VLA, emit a single element, then splat that over the VLA.
  1377. if (vla) Ty = getContext().getBaseElementType(vla);
  1378. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1379. llvm::GlobalVariable *NullVariable =
  1380. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1381. /*isConstant=*/true,
  1382. llvm::GlobalVariable::PrivateLinkage,
  1383. NullConstant, Twine());
  1384. CharUnits NullAlign = DestPtr.getAlignment();
  1385. NullVariable->setAlignment(NullAlign.getQuantity());
  1386. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1387. NullAlign);
  1388. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1389. // Get and call the appropriate llvm.memcpy overload.
  1390. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1391. return;
  1392. }
  1393. // Otherwise, just memset the whole thing to zero. This is legal
  1394. // because in LLVM, all default initializers (other than the ones we just
  1395. // handled above) are guaranteed to have a bit pattern of all zeros.
  1396. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1397. }
  1398. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1399. // Make sure that there is a block for the indirect goto.
  1400. if (!IndirectBranch)
  1401. GetIndirectGotoBlock();
  1402. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1403. // Make sure the indirect branch includes all of the address-taken blocks.
  1404. IndirectBranch->addDestination(BB);
  1405. return llvm::BlockAddress::get(CurFn, BB);
  1406. }
  1407. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1408. // If we already made the indirect branch for indirect goto, return its block.
  1409. if (IndirectBranch) return IndirectBranch->getParent();
  1410. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1411. // Create the PHI node that indirect gotos will add entries to.
  1412. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1413. "indirect.goto.dest");
  1414. // Create the indirect branch instruction.
  1415. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1416. return IndirectBranch->getParent();
  1417. }
  1418. /// Computes the length of an array in elements, as well as the base
  1419. /// element type and a properly-typed first element pointer.
  1420. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1421. QualType &baseType,
  1422. Address &addr) {
  1423. const ArrayType *arrayType = origArrayType;
  1424. // If it's a VLA, we have to load the stored size. Note that
  1425. // this is the size of the VLA in bytes, not its size in elements.
  1426. llvm::Value *numVLAElements = nullptr;
  1427. if (isa<VariableArrayType>(arrayType)) {
  1428. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1429. // Walk into all VLAs. This doesn't require changes to addr,
  1430. // which has type T* where T is the first non-VLA element type.
  1431. do {
  1432. QualType elementType = arrayType->getElementType();
  1433. arrayType = getContext().getAsArrayType(elementType);
  1434. // If we only have VLA components, 'addr' requires no adjustment.
  1435. if (!arrayType) {
  1436. baseType = elementType;
  1437. return numVLAElements;
  1438. }
  1439. } while (isa<VariableArrayType>(arrayType));
  1440. // We get out here only if we find a constant array type
  1441. // inside the VLA.
  1442. }
  1443. // We have some number of constant-length arrays, so addr should
  1444. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1445. // down to the first element of addr.
  1446. SmallVector<llvm::Value*, 8> gepIndices;
  1447. // GEP down to the array type.
  1448. llvm::ConstantInt *zero = Builder.getInt32(0);
  1449. gepIndices.push_back(zero);
  1450. uint64_t countFromCLAs = 1;
  1451. QualType eltType;
  1452. llvm::ArrayType *llvmArrayType =
  1453. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1454. while (llvmArrayType) {
  1455. assert(isa<ConstantArrayType>(arrayType));
  1456. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1457. == llvmArrayType->getNumElements());
  1458. gepIndices.push_back(zero);
  1459. countFromCLAs *= llvmArrayType->getNumElements();
  1460. eltType = arrayType->getElementType();
  1461. llvmArrayType =
  1462. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1463. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1464. assert((!llvmArrayType || arrayType) &&
  1465. "LLVM and Clang types are out-of-synch");
  1466. }
  1467. if (arrayType) {
  1468. // From this point onwards, the Clang array type has been emitted
  1469. // as some other type (probably a packed struct). Compute the array
  1470. // size, and just emit the 'begin' expression as a bitcast.
  1471. while (arrayType) {
  1472. countFromCLAs *=
  1473. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1474. eltType = arrayType->getElementType();
  1475. arrayType = getContext().getAsArrayType(eltType);
  1476. }
  1477. llvm::Type *baseType = ConvertType(eltType);
  1478. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1479. } else {
  1480. // Create the actual GEP.
  1481. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1482. gepIndices, "array.begin"),
  1483. addr.getAlignment());
  1484. }
  1485. baseType = eltType;
  1486. llvm::Value *numElements
  1487. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1488. // If we had any VLA dimensions, factor them in.
  1489. if (numVLAElements)
  1490. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1491. return numElements;
  1492. }
  1493. std::pair<llvm::Value*, QualType>
  1494. CodeGenFunction::getVLASize(QualType type) {
  1495. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1496. assert(vla && "type was not a variable array type!");
  1497. return getVLASize(vla);
  1498. }
  1499. std::pair<llvm::Value*, QualType>
  1500. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1501. // The number of elements so far; always size_t.
  1502. llvm::Value *numElements = nullptr;
  1503. QualType elementType;
  1504. do {
  1505. elementType = type->getElementType();
  1506. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1507. assert(vlaSize && "no size for VLA!");
  1508. assert(vlaSize->getType() == SizeTy);
  1509. if (!numElements) {
  1510. numElements = vlaSize;
  1511. } else {
  1512. // It's undefined behavior if this wraps around, so mark it that way.
  1513. // FIXME: Teach -fsanitize=undefined to trap this.
  1514. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1515. }
  1516. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1517. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1518. }
  1519. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1520. assert(type->isVariablyModifiedType() &&
  1521. "Must pass variably modified type to EmitVLASizes!");
  1522. EnsureInsertPoint();
  1523. // We're going to walk down into the type and look for VLA
  1524. // expressions.
  1525. do {
  1526. assert(type->isVariablyModifiedType());
  1527. const Type *ty = type.getTypePtr();
  1528. switch (ty->getTypeClass()) {
  1529. #define TYPE(Class, Base)
  1530. #define ABSTRACT_TYPE(Class, Base)
  1531. #define NON_CANONICAL_TYPE(Class, Base)
  1532. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1533. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1534. #include "clang/AST/TypeNodes.def"
  1535. llvm_unreachable("unexpected dependent type!");
  1536. // These types are never variably-modified.
  1537. case Type::Builtin:
  1538. case Type::Complex:
  1539. case Type::Vector:
  1540. case Type::ExtVector:
  1541. case Type::Record:
  1542. case Type::Enum:
  1543. case Type::Elaborated:
  1544. case Type::TemplateSpecialization:
  1545. case Type::ObjCTypeParam:
  1546. case Type::ObjCObject:
  1547. case Type::ObjCInterface:
  1548. case Type::ObjCObjectPointer:
  1549. llvm_unreachable("type class is never variably-modified!");
  1550. case Type::Adjusted:
  1551. type = cast<AdjustedType>(ty)->getAdjustedType();
  1552. break;
  1553. case Type::Decayed:
  1554. type = cast<DecayedType>(ty)->getPointeeType();
  1555. break;
  1556. case Type::Pointer:
  1557. type = cast<PointerType>(ty)->getPointeeType();
  1558. break;
  1559. case Type::BlockPointer:
  1560. type = cast<BlockPointerType>(ty)->getPointeeType();
  1561. break;
  1562. case Type::LValueReference:
  1563. case Type::RValueReference:
  1564. type = cast<ReferenceType>(ty)->getPointeeType();
  1565. break;
  1566. case Type::MemberPointer:
  1567. type = cast<MemberPointerType>(ty)->getPointeeType();
  1568. break;
  1569. case Type::ConstantArray:
  1570. case Type::IncompleteArray:
  1571. // Losing element qualification here is fine.
  1572. type = cast<ArrayType>(ty)->getElementType();
  1573. break;
  1574. case Type::VariableArray: {
  1575. // Losing element qualification here is fine.
  1576. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1577. // Unknown size indication requires no size computation.
  1578. // Otherwise, evaluate and record it.
  1579. if (const Expr *size = vat->getSizeExpr()) {
  1580. // It's possible that we might have emitted this already,
  1581. // e.g. with a typedef and a pointer to it.
  1582. llvm::Value *&entry = VLASizeMap[size];
  1583. if (!entry) {
  1584. llvm::Value *Size = EmitScalarExpr(size);
  1585. // C11 6.7.6.2p5:
  1586. // If the size is an expression that is not an integer constant
  1587. // expression [...] each time it is evaluated it shall have a value
  1588. // greater than zero.
  1589. if (SanOpts.has(SanitizerKind::VLABound) &&
  1590. size->getType()->isSignedIntegerType()) {
  1591. SanitizerScope SanScope(this);
  1592. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1593. llvm::Constant *StaticArgs[] = {
  1594. EmitCheckSourceLocation(size->getLocStart()),
  1595. EmitCheckTypeDescriptor(size->getType())
  1596. };
  1597. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1598. SanitizerKind::VLABound),
  1599. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1600. }
  1601. // Always zexting here would be wrong if it weren't
  1602. // undefined behavior to have a negative bound.
  1603. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1604. }
  1605. }
  1606. type = vat->getElementType();
  1607. break;
  1608. }
  1609. case Type::FunctionProto:
  1610. case Type::FunctionNoProto:
  1611. type = cast<FunctionType>(ty)->getReturnType();
  1612. break;
  1613. case Type::Paren:
  1614. case Type::TypeOf:
  1615. case Type::UnaryTransform:
  1616. case Type::Attributed:
  1617. case Type::SubstTemplateTypeParm:
  1618. case Type::PackExpansion:
  1619. // Keep walking after single level desugaring.
  1620. type = type.getSingleStepDesugaredType(getContext());
  1621. break;
  1622. case Type::Typedef:
  1623. case Type::Decltype:
  1624. case Type::Auto:
  1625. // Stop walking: nothing to do.
  1626. return;
  1627. case Type::TypeOfExpr:
  1628. // Stop walking: emit typeof expression.
  1629. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1630. return;
  1631. case Type::Atomic:
  1632. type = cast<AtomicType>(ty)->getValueType();
  1633. break;
  1634. case Type::Pipe:
  1635. type = cast<PipeType>(ty)->getElementType();
  1636. break;
  1637. }
  1638. } while (type->isVariablyModifiedType());
  1639. }
  1640. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1641. if (getContext().getBuiltinVaListType()->isArrayType())
  1642. return EmitPointerWithAlignment(E);
  1643. return EmitLValue(E).getAddress();
  1644. }
  1645. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1646. return EmitLValue(E).getAddress();
  1647. }
  1648. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1649. const APValue &Init) {
  1650. assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
  1651. if (CGDebugInfo *Dbg = getDebugInfo())
  1652. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1653. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1654. }
  1655. CodeGenFunction::PeepholeProtection
  1656. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1657. // At the moment, the only aggressive peephole we do in IR gen
  1658. // is trunc(zext) folding, but if we add more, we can easily
  1659. // extend this protection.
  1660. if (!rvalue.isScalar()) return PeepholeProtection();
  1661. llvm::Value *value = rvalue.getScalarVal();
  1662. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1663. // Just make an extra bitcast.
  1664. assert(HaveInsertPoint());
  1665. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1666. Builder.GetInsertBlock());
  1667. PeepholeProtection protection;
  1668. protection.Inst = inst;
  1669. return protection;
  1670. }
  1671. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1672. if (!protection.Inst) return;
  1673. // In theory, we could try to duplicate the peepholes now, but whatever.
  1674. protection.Inst->eraseFromParent();
  1675. }
  1676. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1677. llvm::Value *AnnotatedVal,
  1678. StringRef AnnotationStr,
  1679. SourceLocation Location) {
  1680. llvm::Value *Args[4] = {
  1681. AnnotatedVal,
  1682. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1683. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1684. CGM.EmitAnnotationLineNo(Location)
  1685. };
  1686. return Builder.CreateCall(AnnotationFn, Args);
  1687. }
  1688. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1689. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1690. // FIXME We create a new bitcast for every annotation because that's what
  1691. // llvm-gcc was doing.
  1692. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1693. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1694. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1695. I->getAnnotation(), D->getLocation());
  1696. }
  1697. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1698. Address Addr) {
  1699. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1700. llvm::Value *V = Addr.getPointer();
  1701. llvm::Type *VTy = V->getType();
  1702. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1703. CGM.Int8PtrTy);
  1704. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1705. // FIXME Always emit the cast inst so we can differentiate between
  1706. // annotation on the first field of a struct and annotation on the struct
  1707. // itself.
  1708. if (VTy != CGM.Int8PtrTy)
  1709. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1710. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1711. V = Builder.CreateBitCast(V, VTy);
  1712. }
  1713. return Address(V, Addr.getAlignment());
  1714. }
  1715. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1716. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1717. : CGF(CGF) {
  1718. assert(!CGF->IsSanitizerScope);
  1719. CGF->IsSanitizerScope = true;
  1720. }
  1721. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1722. CGF->IsSanitizerScope = false;
  1723. }
  1724. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1725. const llvm::Twine &Name,
  1726. llvm::BasicBlock *BB,
  1727. llvm::BasicBlock::iterator InsertPt) const {
  1728. LoopStack.InsertHelper(I);
  1729. if (IsSanitizerScope)
  1730. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1731. }
  1732. void CGBuilderInserter::InsertHelper(
  1733. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1734. llvm::BasicBlock::iterator InsertPt) const {
  1735. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1736. if (CGF)
  1737. CGF->InsertHelper(I, Name, BB, InsertPt);
  1738. }
  1739. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1740. CodeGenModule &CGM, const FunctionDecl *FD,
  1741. std::string &FirstMissing) {
  1742. // If there aren't any required features listed then go ahead and return.
  1743. if (ReqFeatures.empty())
  1744. return false;
  1745. // Now build up the set of caller features and verify that all the required
  1746. // features are there.
  1747. llvm::StringMap<bool> CallerFeatureMap;
  1748. CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
  1749. // If we have at least one of the features in the feature list return
  1750. // true, otherwise return false.
  1751. return std::all_of(
  1752. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1753. SmallVector<StringRef, 1> OrFeatures;
  1754. Feature.split(OrFeatures, "|");
  1755. return std::any_of(OrFeatures.begin(), OrFeatures.end(),
  1756. [&](StringRef Feature) {
  1757. if (!CallerFeatureMap.lookup(Feature)) {
  1758. FirstMissing = Feature.str();
  1759. return false;
  1760. }
  1761. return true;
  1762. });
  1763. });
  1764. }
  1765. // Emits an error if we don't have a valid set of target features for the
  1766. // called function.
  1767. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1768. const FunctionDecl *TargetDecl) {
  1769. // Early exit if this is an indirect call.
  1770. if (!TargetDecl)
  1771. return;
  1772. // Get the current enclosing function if it exists. If it doesn't
  1773. // we can't check the target features anyhow.
  1774. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1775. if (!FD)
  1776. return;
  1777. // Grab the required features for the call. For a builtin this is listed in
  1778. // the td file with the default cpu, for an always_inline function this is any
  1779. // listed cpu and any listed features.
  1780. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1781. std::string MissingFeature;
  1782. if (BuiltinID) {
  1783. SmallVector<StringRef, 1> ReqFeatures;
  1784. const char *FeatureList =
  1785. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1786. // Return if the builtin doesn't have any required features.
  1787. if (!FeatureList || StringRef(FeatureList) == "")
  1788. return;
  1789. StringRef(FeatureList).split(ReqFeatures, ",");
  1790. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1791. CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
  1792. << TargetDecl->getDeclName()
  1793. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1794. } else if (TargetDecl->hasAttr<TargetAttr>()) {
  1795. // Get the required features for the callee.
  1796. SmallVector<StringRef, 1> ReqFeatures;
  1797. llvm::StringMap<bool> CalleeFeatureMap;
  1798. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1799. for (const auto &F : CalleeFeatureMap) {
  1800. // Only positive features are "required".
  1801. if (F.getValue())
  1802. ReqFeatures.push_back(F.getKey());
  1803. }
  1804. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1805. CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
  1806. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1807. }
  1808. }
  1809. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1810. if (!CGM.getCodeGenOpts().SanitizeStats)
  1811. return;
  1812. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1813. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1814. CGM.getSanStats().create(IRB, SSK);
  1815. }
  1816. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  1817. if (CGDebugInfo *DI = getDebugInfo())
  1818. return DI->SourceLocToDebugLoc(Location);
  1819. return llvm::DebugLoc();
  1820. }