CodeGenFunction.cpp 80 KB

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