CodeGenFunction.cpp 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  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) {
  106. CGM.getOpenMPRuntime().functionFinished(*this);
  107. }
  108. }
  109. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  110. AlignmentSource *Source) {
  111. return getNaturalTypeAlignment(T->getPointeeType(), Source,
  112. /*forPointee*/ true);
  113. }
  114. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  115. AlignmentSource *Source,
  116. bool forPointeeType) {
  117. // Honor alignment typedef attributes even on incomplete types.
  118. // We also honor them straight for C++ class types, even as pointees;
  119. // there's an expressivity gap here.
  120. if (auto TT = T->getAs<TypedefType>()) {
  121. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  122. if (Source) *Source = AlignmentSource::AttributedType;
  123. return getContext().toCharUnitsFromBits(Align);
  124. }
  125. }
  126. if (Source) *Source = AlignmentSource::Type;
  127. CharUnits Alignment;
  128. if (T->isIncompleteType()) {
  129. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  130. } else {
  131. // For C++ class pointees, we don't know whether we're pointing at a
  132. // base or a complete object, so we generally need to use the
  133. // non-virtual alignment.
  134. const CXXRecordDecl *RD;
  135. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  136. Alignment = CGM.getClassPointerAlignment(RD);
  137. } else {
  138. Alignment = getContext().getTypeAlignInChars(T);
  139. }
  140. // Cap to the global maximum type alignment unless the alignment
  141. // was somehow explicit on the type.
  142. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  143. if (Alignment.getQuantity() > MaxAlign &&
  144. !getContext().isAlignmentRequired(T))
  145. Alignment = CharUnits::fromQuantity(MaxAlign);
  146. }
  147. }
  148. return Alignment;
  149. }
  150. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  151. AlignmentSource AlignSource;
  152. CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource);
  153. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource,
  154. CGM.getTBAAInfo(T));
  155. }
  156. /// Given a value of type T* that may not be to a complete object,
  157. /// construct an l-value with the natural pointee alignment of T.
  158. LValue
  159. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  160. AlignmentSource AlignSource;
  161. CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true);
  162. return MakeAddrLValue(Address(V, Align), T, AlignSource);
  163. }
  164. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  165. return CGM.getTypes().ConvertTypeForMem(T);
  166. }
  167. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  168. return CGM.getTypes().ConvertType(T);
  169. }
  170. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  171. type = type.getCanonicalType();
  172. while (true) {
  173. switch (type->getTypeClass()) {
  174. #define TYPE(name, parent)
  175. #define ABSTRACT_TYPE(name, parent)
  176. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  177. #define DEPENDENT_TYPE(name, parent) case Type::name:
  178. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  179. #include "clang/AST/TypeNodes.def"
  180. llvm_unreachable("non-canonical or dependent type in IR-generation");
  181. case Type::Auto:
  182. llvm_unreachable("undeduced auto 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. Fn->addFnAttr("counting-function", getTarget().getMCountName());
  748. if (RetTy->isVoidType()) {
  749. // Void type; nothing to return.
  750. ReturnValue = Address::invalid();
  751. // Count the implicit return.
  752. if (!endsWithReturn(D))
  753. ++NumReturnExprs;
  754. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  755. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  756. // Indirect aggregate return; emit returned value directly into sret slot.
  757. // This reduces code size, and affects correctness in C++.
  758. auto AI = CurFn->arg_begin();
  759. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  760. ++AI;
  761. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  762. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  763. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  764. // Load the sret pointer from the argument struct and return into that.
  765. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  766. llvm::Function::arg_iterator EI = CurFn->arg_end();
  767. --EI;
  768. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  769. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  770. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  771. } else {
  772. ReturnValue = CreateIRTemp(RetTy, "retval");
  773. // Tell the epilog emitter to autorelease the result. We do this
  774. // now so that various specialized functions can suppress it
  775. // during their IR-generation.
  776. if (getLangOpts().ObjCAutoRefCount &&
  777. !CurFnInfo->isReturnsRetained() &&
  778. RetTy->isObjCRetainableType())
  779. AutoreleaseResult = true;
  780. }
  781. EmitStartEHSpec(CurCodeDecl);
  782. PrologueCleanupDepth = EHStack.stable_begin();
  783. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  784. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  785. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  786. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  787. if (MD->getParent()->isLambda() &&
  788. MD->getOverloadedOperator() == OO_Call) {
  789. // We're in a lambda; figure out the captures.
  790. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  791. LambdaThisCaptureField);
  792. if (LambdaThisCaptureField) {
  793. // If the lambda captures the object referred to by '*this' - either by
  794. // value or by reference, make sure CXXThisValue points to the correct
  795. // object.
  796. // Get the lvalue for the field (which is a copy of the enclosing object
  797. // or contains the address of the enclosing object).
  798. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  799. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  800. // If the enclosing object was captured by value, just use its address.
  801. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  802. } else {
  803. // Load the lvalue pointed to by the field, since '*this' was captured
  804. // by reference.
  805. CXXThisValue =
  806. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  807. }
  808. }
  809. for (auto *FD : MD->getParent()->fields()) {
  810. if (FD->hasCapturedVLAType()) {
  811. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  812. SourceLocation()).getScalarVal();
  813. auto VAT = FD->getCapturedVLAType();
  814. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  815. }
  816. }
  817. } else {
  818. // Not in a lambda; just use 'this' from the method.
  819. // FIXME: Should we generate a new load for each use of 'this'? The
  820. // fast register allocator would be happier...
  821. CXXThisValue = CXXABIThisValue;
  822. }
  823. }
  824. // If any of the arguments have a variably modified type, make sure to
  825. // emit the type size.
  826. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  827. i != e; ++i) {
  828. const VarDecl *VD = *i;
  829. // Dig out the type as written from ParmVarDecls; it's unclear whether
  830. // the standard (C99 6.9.1p10) requires this, but we're following the
  831. // precedent set by gcc.
  832. QualType Ty;
  833. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  834. Ty = PVD->getOriginalType();
  835. else
  836. Ty = VD->getType();
  837. if (Ty->isVariablyModifiedType())
  838. EmitVariablyModifiedType(Ty);
  839. }
  840. // Emit a location at the end of the prologue.
  841. if (CGDebugInfo *DI = getDebugInfo())
  842. DI->EmitLocation(Builder, StartLoc);
  843. }
  844. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  845. const Stmt *Body) {
  846. incrementProfileCounter(Body);
  847. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  848. EmitCompoundStmtWithoutScope(*S);
  849. else
  850. EmitStmt(Body);
  851. }
  852. /// When instrumenting to collect profile data, the counts for some blocks
  853. /// such as switch cases need to not include the fall-through counts, so
  854. /// emit a branch around the instrumentation code. When not instrumenting,
  855. /// this just calls EmitBlock().
  856. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  857. const Stmt *S) {
  858. llvm::BasicBlock *SkipCountBB = nullptr;
  859. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  860. // When instrumenting for profiling, the fallthrough to certain
  861. // statements needs to skip over the instrumentation code so that we
  862. // get an accurate count.
  863. SkipCountBB = createBasicBlock("skipcount");
  864. EmitBranch(SkipCountBB);
  865. }
  866. EmitBlock(BB);
  867. uint64_t CurrentCount = getCurrentProfileCount();
  868. incrementProfileCounter(S);
  869. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  870. if (SkipCountBB)
  871. EmitBlock(SkipCountBB);
  872. }
  873. /// Tries to mark the given function nounwind based on the
  874. /// non-existence of any throwing calls within it. We believe this is
  875. /// lightweight enough to do at -O0.
  876. static void TryMarkNoThrow(llvm::Function *F) {
  877. // LLVM treats 'nounwind' on a function as part of the type, so we
  878. // can't do this on functions that can be overwritten.
  879. if (F->isInterposable()) return;
  880. for (llvm::BasicBlock &BB : *F)
  881. for (llvm::Instruction &I : BB)
  882. if (I.mayThrow())
  883. return;
  884. F->setDoesNotThrow();
  885. }
  886. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  887. FunctionArgList &Args) {
  888. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  889. QualType ResTy = FD->getReturnType();
  890. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  891. if (MD && MD->isInstance()) {
  892. if (CGM.getCXXABI().HasThisReturn(GD))
  893. ResTy = MD->getThisType(getContext());
  894. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  895. ResTy = CGM.getContext().VoidPtrTy;
  896. CGM.getCXXABI().buildThisParam(*this, Args);
  897. }
  898. // The base version of an inheriting constructor whose constructed base is a
  899. // virtual base is not passed any arguments (because it doesn't actually call
  900. // the inherited constructor).
  901. bool PassedParams = true;
  902. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  903. if (auto Inherited = CD->getInheritedConstructor())
  904. PassedParams =
  905. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  906. if (PassedParams) {
  907. for (auto *Param : FD->parameters()) {
  908. Args.push_back(Param);
  909. if (!Param->hasAttr<PassObjectSizeAttr>())
  910. continue;
  911. IdentifierInfo *NoID = nullptr;
  912. auto *Implicit = ImplicitParamDecl::Create(
  913. getContext(), Param->getDeclContext(), Param->getLocation(), NoID,
  914. getContext().getSizeType());
  915. SizeArguments[Param] = Implicit;
  916. Args.push_back(Implicit);
  917. }
  918. }
  919. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  920. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  921. return ResTy;
  922. }
  923. static bool
  924. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  925. const ASTContext &Context) {
  926. QualType T = FD->getReturnType();
  927. // Avoid the optimization for functions that return a record type with a
  928. // trivial destructor or another trivially copyable type.
  929. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  930. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  931. return !ClassDecl->hasTrivialDestructor();
  932. }
  933. return !T.isTriviallyCopyableType(Context);
  934. }
  935. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  936. const CGFunctionInfo &FnInfo) {
  937. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  938. CurGD = GD;
  939. FunctionArgList Args;
  940. QualType ResTy = BuildFunctionArgList(GD, Args);
  941. // Check if we should generate debug info for this function.
  942. if (FD->hasAttr<NoDebugAttr>())
  943. DebugInfo = nullptr; // disable debug info indefinitely for this function
  944. SourceRange BodyRange;
  945. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  946. CurEHLocation = BodyRange.getEnd();
  947. // Use the location of the start of the function to determine where
  948. // the function definition is located. By default use the location
  949. // of the declaration as the location for the subprogram. A function
  950. // may lack a declaration in the source code if it is created by code
  951. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  952. SourceLocation Loc = FD->getLocation();
  953. // If this is a function specialization then use the pattern body
  954. // as the location for the function.
  955. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  956. if (SpecDecl->hasBody(SpecDecl))
  957. Loc = SpecDecl->getLocation();
  958. Stmt *Body = FD->getBody();
  959. // Initialize helper which will detect jumps which can cause invalid lifetime
  960. // markers.
  961. if (Body && ShouldEmitLifetimeMarkers)
  962. Bypasses.Init(Body);
  963. // Emit the standard function prologue.
  964. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  965. // Generate the body of the function.
  966. PGO.assignRegionCounters(GD, CurFn);
  967. if (isa<CXXDestructorDecl>(FD))
  968. EmitDestructorBody(Args);
  969. else if (isa<CXXConstructorDecl>(FD))
  970. EmitConstructorBody(Args);
  971. else if (getLangOpts().CUDA &&
  972. !getLangOpts().CUDAIsDevice &&
  973. FD->hasAttr<CUDAGlobalAttr>())
  974. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  975. else if (isa<CXXConversionDecl>(FD) &&
  976. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  977. // The lambda conversion to block pointer is special; the semantics can't be
  978. // expressed in the AST, so IRGen needs to special-case it.
  979. EmitLambdaToBlockPointerBody(Args);
  980. } else if (isa<CXXMethodDecl>(FD) &&
  981. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  982. // The lambda static invoker function is special, because it forwards or
  983. // clones the body of the function call operator (but is actually static).
  984. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  985. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  986. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  987. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  988. // Implicit copy-assignment gets the same special treatment as implicit
  989. // copy-constructors.
  990. emitImplicitAssignmentOperatorBody(Args);
  991. } else if (Body) {
  992. EmitFunctionBody(Args, Body);
  993. } else
  994. llvm_unreachable("no definition for emitted function");
  995. // C++11 [stmt.return]p2:
  996. // Flowing off the end of a function [...] results in undefined behavior in
  997. // a value-returning function.
  998. // C11 6.9.1p12:
  999. // If the '}' that terminates a function is reached, and the value of the
  1000. // function call is used by the caller, the behavior is undefined.
  1001. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1002. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1003. bool ShouldEmitUnreachable =
  1004. CGM.getCodeGenOpts().StrictReturn ||
  1005. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1006. if (SanOpts.has(SanitizerKind::Return)) {
  1007. SanitizerScope SanScope(this);
  1008. llvm::Value *IsFalse = Builder.getFalse();
  1009. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1010. SanitizerHandler::MissingReturn,
  1011. EmitCheckSourceLocation(FD->getLocation()), None);
  1012. } else if (ShouldEmitUnreachable) {
  1013. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1014. EmitTrapCall(llvm::Intrinsic::trap);
  1015. }
  1016. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1017. Builder.CreateUnreachable();
  1018. Builder.ClearInsertionPoint();
  1019. }
  1020. }
  1021. // Emit the standard function epilogue.
  1022. FinishFunction(BodyRange.getEnd());
  1023. // If we haven't marked the function nothrow through other means, do
  1024. // a quick pass now to see if we can.
  1025. if (!CurFn->doesNotThrow())
  1026. TryMarkNoThrow(CurFn);
  1027. }
  1028. /// ContainsLabel - Return true if the statement contains a label in it. If
  1029. /// this statement is not executed normally, it not containing a label means
  1030. /// that we can just remove the code.
  1031. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1032. // Null statement, not a label!
  1033. if (!S) return false;
  1034. // If this is a label, we have to emit the code, consider something like:
  1035. // if (0) { ... foo: bar(); } goto foo;
  1036. //
  1037. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1038. // can't jump to one from outside their declared region.
  1039. if (isa<LabelStmt>(S))
  1040. return true;
  1041. // If this is a case/default statement, and we haven't seen a switch, we have
  1042. // to emit the code.
  1043. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1044. return true;
  1045. // If this is a switch statement, we want to ignore cases below it.
  1046. if (isa<SwitchStmt>(S))
  1047. IgnoreCaseStmts = true;
  1048. // Scan subexpressions for verboten labels.
  1049. for (const Stmt *SubStmt : S->children())
  1050. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1051. return true;
  1052. return false;
  1053. }
  1054. /// containsBreak - Return true if the statement contains a break out of it.
  1055. /// If the statement (recursively) contains a switch or loop with a break
  1056. /// inside of it, this is fine.
  1057. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1058. // Null statement, not a label!
  1059. if (!S) return false;
  1060. // If this is a switch or loop that defines its own break scope, then we can
  1061. // include it and anything inside of it.
  1062. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1063. isa<ForStmt>(S))
  1064. return false;
  1065. if (isa<BreakStmt>(S))
  1066. return true;
  1067. // Scan subexpressions for verboten breaks.
  1068. for (const Stmt *SubStmt : S->children())
  1069. if (containsBreak(SubStmt))
  1070. return true;
  1071. return false;
  1072. }
  1073. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1074. if (!S) return false;
  1075. // Some statement kinds add a scope and thus never add a decl to the current
  1076. // scope. Note, this list is longer than the list of statements that might
  1077. // have an unscoped decl nested within them, but this way is conservatively
  1078. // correct even if more statement kinds are added.
  1079. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1080. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1081. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1082. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1083. return false;
  1084. if (isa<DeclStmt>(S))
  1085. return true;
  1086. for (const Stmt *SubStmt : S->children())
  1087. if (mightAddDeclToScope(SubStmt))
  1088. return true;
  1089. return false;
  1090. }
  1091. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1092. /// to a constant, or if it does but contains a label, return false. If it
  1093. /// constant folds return true and set the boolean result in Result.
  1094. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1095. bool &ResultBool,
  1096. bool AllowLabels) {
  1097. llvm::APSInt ResultInt;
  1098. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1099. return false;
  1100. ResultBool = ResultInt.getBoolValue();
  1101. return true;
  1102. }
  1103. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1104. /// to a constant, or if it does but contains a label, return false. If it
  1105. /// constant folds return true and set the folded value.
  1106. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1107. llvm::APSInt &ResultInt,
  1108. bool AllowLabels) {
  1109. // FIXME: Rename and handle conversion of other evaluatable things
  1110. // to bool.
  1111. llvm::APSInt Int;
  1112. if (!Cond->EvaluateAsInt(Int, getContext()))
  1113. return false; // Not foldable, not integer or not fully evaluatable.
  1114. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1115. return false; // Contains a label.
  1116. ResultInt = Int;
  1117. return true;
  1118. }
  1119. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1120. /// statement) to the specified blocks. Based on the condition, this might try
  1121. /// to simplify the codegen of the conditional based on the branch.
  1122. ///
  1123. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1124. llvm::BasicBlock *TrueBlock,
  1125. llvm::BasicBlock *FalseBlock,
  1126. uint64_t TrueCount) {
  1127. Cond = Cond->IgnoreParens();
  1128. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1129. // Handle X && Y in a condition.
  1130. if (CondBOp->getOpcode() == BO_LAnd) {
  1131. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1132. // folded if the case was simple enough.
  1133. bool ConstantBool = false;
  1134. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1135. ConstantBool) {
  1136. // br(1 && X) -> br(X).
  1137. incrementProfileCounter(CondBOp);
  1138. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1139. TrueCount);
  1140. }
  1141. // If we have "X && 1", simplify the code to use an uncond branch.
  1142. // "X && 0" would have been constant folded to 0.
  1143. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1144. ConstantBool) {
  1145. // br(X && 1) -> br(X).
  1146. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1147. TrueCount);
  1148. }
  1149. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1150. // want to jump to the FalseBlock.
  1151. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1152. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1153. // can be propagated to that branch.
  1154. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1155. ConditionalEvaluation eval(*this);
  1156. {
  1157. ApplyDebugLocation DL(*this, Cond);
  1158. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1159. EmitBlock(LHSTrue);
  1160. }
  1161. incrementProfileCounter(CondBOp);
  1162. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1163. // Any temporaries created here are conditional.
  1164. eval.begin(*this);
  1165. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1166. eval.end(*this);
  1167. return;
  1168. }
  1169. if (CondBOp->getOpcode() == BO_LOr) {
  1170. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1171. // folded if the case was simple enough.
  1172. bool ConstantBool = false;
  1173. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1174. !ConstantBool) {
  1175. // br(0 || X) -> br(X).
  1176. incrementProfileCounter(CondBOp);
  1177. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1178. TrueCount);
  1179. }
  1180. // If we have "X || 0", simplify the code to use an uncond branch.
  1181. // "X || 1" would have been constant folded to 1.
  1182. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1183. !ConstantBool) {
  1184. // br(X || 0) -> br(X).
  1185. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1186. TrueCount);
  1187. }
  1188. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1189. // want to jump to the TrueBlock.
  1190. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1191. // We have the count for entry to the RHS and for the whole expression
  1192. // being true, so we can divy up True count between the short circuit and
  1193. // the RHS.
  1194. uint64_t LHSCount =
  1195. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1196. uint64_t RHSCount = TrueCount - LHSCount;
  1197. ConditionalEvaluation eval(*this);
  1198. {
  1199. ApplyDebugLocation DL(*this, Cond);
  1200. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1201. EmitBlock(LHSFalse);
  1202. }
  1203. incrementProfileCounter(CondBOp);
  1204. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1205. // Any temporaries created here are conditional.
  1206. eval.begin(*this);
  1207. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1208. eval.end(*this);
  1209. return;
  1210. }
  1211. }
  1212. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1213. // br(!x, t, f) -> br(x, f, t)
  1214. if (CondUOp->getOpcode() == UO_LNot) {
  1215. // Negate the count.
  1216. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1217. // Negate the condition and swap the destination blocks.
  1218. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1219. FalseCount);
  1220. }
  1221. }
  1222. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1223. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1224. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1225. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1226. ConditionalEvaluation cond(*this);
  1227. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1228. getProfileCount(CondOp));
  1229. // When computing PGO branch weights, we only know the overall count for
  1230. // the true block. This code is essentially doing tail duplication of the
  1231. // naive code-gen, introducing new edges for which counts are not
  1232. // available. Divide the counts proportionally between the LHS and RHS of
  1233. // the conditional operator.
  1234. uint64_t LHSScaledTrueCount = 0;
  1235. if (TrueCount) {
  1236. double LHSRatio =
  1237. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1238. LHSScaledTrueCount = TrueCount * LHSRatio;
  1239. }
  1240. cond.begin(*this);
  1241. EmitBlock(LHSBlock);
  1242. incrementProfileCounter(CondOp);
  1243. {
  1244. ApplyDebugLocation DL(*this, Cond);
  1245. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1246. LHSScaledTrueCount);
  1247. }
  1248. cond.end(*this);
  1249. cond.begin(*this);
  1250. EmitBlock(RHSBlock);
  1251. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1252. TrueCount - LHSScaledTrueCount);
  1253. cond.end(*this);
  1254. return;
  1255. }
  1256. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1257. // Conditional operator handling can give us a throw expression as a
  1258. // condition for a case like:
  1259. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1260. // Fold this to:
  1261. // br(c, throw x, br(y, t, f))
  1262. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1263. return;
  1264. }
  1265. // If the branch has a condition wrapped by __builtin_unpredictable,
  1266. // create metadata that specifies that the branch is unpredictable.
  1267. // Don't bother if not optimizing because that metadata would not be used.
  1268. llvm::MDNode *Unpredictable = nullptr;
  1269. auto *Call = dyn_cast<CallExpr>(Cond);
  1270. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1271. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1272. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1273. llvm::MDBuilder MDHelper(getLLVMContext());
  1274. Unpredictable = MDHelper.createUnpredictable();
  1275. }
  1276. }
  1277. // Create branch weights based on the number of times we get here and the
  1278. // number of times the condition should be true.
  1279. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1280. llvm::MDNode *Weights =
  1281. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1282. // Emit the code with the fully general case.
  1283. llvm::Value *CondV;
  1284. {
  1285. ApplyDebugLocation DL(*this, Cond);
  1286. CondV = EvaluateExprAsBool(Cond);
  1287. }
  1288. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1289. }
  1290. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1291. /// specified stmt yet.
  1292. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1293. CGM.ErrorUnsupported(S, Type);
  1294. }
  1295. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1296. /// variable-length array whose elements have a non-zero bit-pattern.
  1297. ///
  1298. /// \param baseType the inner-most element type of the array
  1299. /// \param src - a char* pointing to the bit-pattern for a single
  1300. /// base element of the array
  1301. /// \param sizeInChars - the total size of the VLA, in chars
  1302. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1303. Address dest, Address src,
  1304. llvm::Value *sizeInChars) {
  1305. CGBuilderTy &Builder = CGF.Builder;
  1306. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1307. llvm::Value *baseSizeInChars
  1308. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1309. Address begin =
  1310. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1311. llvm::Value *end =
  1312. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1313. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1314. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1315. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1316. // Make a loop over the VLA. C99 guarantees that the VLA element
  1317. // count must be nonzero.
  1318. CGF.EmitBlock(loopBB);
  1319. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1320. cur->addIncoming(begin.getPointer(), originBB);
  1321. CharUnits curAlign =
  1322. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1323. // memcpy the individual element bit-pattern.
  1324. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1325. /*volatile*/ false);
  1326. // Go to the next element.
  1327. llvm::Value *next =
  1328. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1329. // Leave if that's the end of the VLA.
  1330. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1331. Builder.CreateCondBr(done, contBB, loopBB);
  1332. cur->addIncoming(next, loopBB);
  1333. CGF.EmitBlock(contBB);
  1334. }
  1335. void
  1336. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1337. // Ignore empty classes in C++.
  1338. if (getLangOpts().CPlusPlus) {
  1339. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1340. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1341. return;
  1342. }
  1343. }
  1344. // Cast the dest ptr to the appropriate i8 pointer type.
  1345. if (DestPtr.getElementType() != Int8Ty)
  1346. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1347. // Get size and alignment info for this aggregate.
  1348. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1349. llvm::Value *SizeVal;
  1350. const VariableArrayType *vla;
  1351. // Don't bother emitting a zero-byte memset.
  1352. if (size.isZero()) {
  1353. // But note that getTypeInfo returns 0 for a VLA.
  1354. if (const VariableArrayType *vlaType =
  1355. dyn_cast_or_null<VariableArrayType>(
  1356. getContext().getAsArrayType(Ty))) {
  1357. QualType eltType;
  1358. llvm::Value *numElts;
  1359. std::tie(numElts, eltType) = getVLASize(vlaType);
  1360. SizeVal = numElts;
  1361. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1362. if (!eltSize.isOne())
  1363. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1364. vla = vlaType;
  1365. } else {
  1366. return;
  1367. }
  1368. } else {
  1369. SizeVal = CGM.getSize(size);
  1370. vla = nullptr;
  1371. }
  1372. // If the type contains a pointer to data member we can't memset it to zero.
  1373. // Instead, create a null constant and copy it to the destination.
  1374. // TODO: there are other patterns besides zero that we can usefully memset,
  1375. // like -1, which happens to be the pattern used by member-pointers.
  1376. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1377. // For a VLA, emit a single element, then splat that over the VLA.
  1378. if (vla) Ty = getContext().getBaseElementType(vla);
  1379. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1380. llvm::GlobalVariable *NullVariable =
  1381. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1382. /*isConstant=*/true,
  1383. llvm::GlobalVariable::PrivateLinkage,
  1384. NullConstant, Twine());
  1385. CharUnits NullAlign = DestPtr.getAlignment();
  1386. NullVariable->setAlignment(NullAlign.getQuantity());
  1387. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1388. NullAlign);
  1389. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1390. // Get and call the appropriate llvm.memcpy overload.
  1391. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1392. return;
  1393. }
  1394. // Otherwise, just memset the whole thing to zero. This is legal
  1395. // because in LLVM, all default initializers (other than the ones we just
  1396. // handled above) are guaranteed to have a bit pattern of all zeros.
  1397. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1398. }
  1399. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1400. // Make sure that there is a block for the indirect goto.
  1401. if (!IndirectBranch)
  1402. GetIndirectGotoBlock();
  1403. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1404. // Make sure the indirect branch includes all of the address-taken blocks.
  1405. IndirectBranch->addDestination(BB);
  1406. return llvm::BlockAddress::get(CurFn, BB);
  1407. }
  1408. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1409. // If we already made the indirect branch for indirect goto, return its block.
  1410. if (IndirectBranch) return IndirectBranch->getParent();
  1411. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1412. // Create the PHI node that indirect gotos will add entries to.
  1413. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1414. "indirect.goto.dest");
  1415. // Create the indirect branch instruction.
  1416. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1417. return IndirectBranch->getParent();
  1418. }
  1419. /// Computes the length of an array in elements, as well as the base
  1420. /// element type and a properly-typed first element pointer.
  1421. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1422. QualType &baseType,
  1423. Address &addr) {
  1424. const ArrayType *arrayType = origArrayType;
  1425. // If it's a VLA, we have to load the stored size. Note that
  1426. // this is the size of the VLA in bytes, not its size in elements.
  1427. llvm::Value *numVLAElements = nullptr;
  1428. if (isa<VariableArrayType>(arrayType)) {
  1429. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1430. // Walk into all VLAs. This doesn't require changes to addr,
  1431. // which has type T* where T is the first non-VLA element type.
  1432. do {
  1433. QualType elementType = arrayType->getElementType();
  1434. arrayType = getContext().getAsArrayType(elementType);
  1435. // If we only have VLA components, 'addr' requires no adjustment.
  1436. if (!arrayType) {
  1437. baseType = elementType;
  1438. return numVLAElements;
  1439. }
  1440. } while (isa<VariableArrayType>(arrayType));
  1441. // We get out here only if we find a constant array type
  1442. // inside the VLA.
  1443. }
  1444. // We have some number of constant-length arrays, so addr should
  1445. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1446. // down to the first element of addr.
  1447. SmallVector<llvm::Value*, 8> gepIndices;
  1448. // GEP down to the array type.
  1449. llvm::ConstantInt *zero = Builder.getInt32(0);
  1450. gepIndices.push_back(zero);
  1451. uint64_t countFromCLAs = 1;
  1452. QualType eltType;
  1453. llvm::ArrayType *llvmArrayType =
  1454. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1455. while (llvmArrayType) {
  1456. assert(isa<ConstantArrayType>(arrayType));
  1457. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1458. == llvmArrayType->getNumElements());
  1459. gepIndices.push_back(zero);
  1460. countFromCLAs *= llvmArrayType->getNumElements();
  1461. eltType = arrayType->getElementType();
  1462. llvmArrayType =
  1463. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1464. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1465. assert((!llvmArrayType || arrayType) &&
  1466. "LLVM and Clang types are out-of-synch");
  1467. }
  1468. if (arrayType) {
  1469. // From this point onwards, the Clang array type has been emitted
  1470. // as some other type (probably a packed struct). Compute the array
  1471. // size, and just emit the 'begin' expression as a bitcast.
  1472. while (arrayType) {
  1473. countFromCLAs *=
  1474. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1475. eltType = arrayType->getElementType();
  1476. arrayType = getContext().getAsArrayType(eltType);
  1477. }
  1478. llvm::Type *baseType = ConvertType(eltType);
  1479. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1480. } else {
  1481. // Create the actual GEP.
  1482. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1483. gepIndices, "array.begin"),
  1484. addr.getAlignment());
  1485. }
  1486. baseType = eltType;
  1487. llvm::Value *numElements
  1488. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1489. // If we had any VLA dimensions, factor them in.
  1490. if (numVLAElements)
  1491. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1492. return numElements;
  1493. }
  1494. std::pair<llvm::Value*, QualType>
  1495. CodeGenFunction::getVLASize(QualType type) {
  1496. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1497. assert(vla && "type was not a variable array type!");
  1498. return getVLASize(vla);
  1499. }
  1500. std::pair<llvm::Value*, QualType>
  1501. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1502. // The number of elements so far; always size_t.
  1503. llvm::Value *numElements = nullptr;
  1504. QualType elementType;
  1505. do {
  1506. elementType = type->getElementType();
  1507. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1508. assert(vlaSize && "no size for VLA!");
  1509. assert(vlaSize->getType() == SizeTy);
  1510. if (!numElements) {
  1511. numElements = vlaSize;
  1512. } else {
  1513. // It's undefined behavior if this wraps around, so mark it that way.
  1514. // FIXME: Teach -fsanitize=undefined to trap this.
  1515. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1516. }
  1517. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1518. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1519. }
  1520. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1521. assert(type->isVariablyModifiedType() &&
  1522. "Must pass variably modified type to EmitVLASizes!");
  1523. EnsureInsertPoint();
  1524. // We're going to walk down into the type and look for VLA
  1525. // expressions.
  1526. do {
  1527. assert(type->isVariablyModifiedType());
  1528. const Type *ty = type.getTypePtr();
  1529. switch (ty->getTypeClass()) {
  1530. #define TYPE(Class, Base)
  1531. #define ABSTRACT_TYPE(Class, Base)
  1532. #define NON_CANONICAL_TYPE(Class, Base)
  1533. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1534. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1535. #include "clang/AST/TypeNodes.def"
  1536. llvm_unreachable("unexpected dependent type!");
  1537. // These types are never variably-modified.
  1538. case Type::Builtin:
  1539. case Type::Complex:
  1540. case Type::Vector:
  1541. case Type::ExtVector:
  1542. case Type::Record:
  1543. case Type::Enum:
  1544. case Type::Elaborated:
  1545. case Type::TemplateSpecialization:
  1546. case Type::ObjCTypeParam:
  1547. case Type::ObjCObject:
  1548. case Type::ObjCInterface:
  1549. case Type::ObjCObjectPointer:
  1550. llvm_unreachable("type class is never variably-modified!");
  1551. case Type::Adjusted:
  1552. type = cast<AdjustedType>(ty)->getAdjustedType();
  1553. break;
  1554. case Type::Decayed:
  1555. type = cast<DecayedType>(ty)->getPointeeType();
  1556. break;
  1557. case Type::Pointer:
  1558. type = cast<PointerType>(ty)->getPointeeType();
  1559. break;
  1560. case Type::BlockPointer:
  1561. type = cast<BlockPointerType>(ty)->getPointeeType();
  1562. break;
  1563. case Type::LValueReference:
  1564. case Type::RValueReference:
  1565. type = cast<ReferenceType>(ty)->getPointeeType();
  1566. break;
  1567. case Type::MemberPointer:
  1568. type = cast<MemberPointerType>(ty)->getPointeeType();
  1569. break;
  1570. case Type::ConstantArray:
  1571. case Type::IncompleteArray:
  1572. // Losing element qualification here is fine.
  1573. type = cast<ArrayType>(ty)->getElementType();
  1574. break;
  1575. case Type::VariableArray: {
  1576. // Losing element qualification here is fine.
  1577. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1578. // Unknown size indication requires no size computation.
  1579. // Otherwise, evaluate and record it.
  1580. if (const Expr *size = vat->getSizeExpr()) {
  1581. // It's possible that we might have emitted this already,
  1582. // e.g. with a typedef and a pointer to it.
  1583. llvm::Value *&entry = VLASizeMap[size];
  1584. if (!entry) {
  1585. llvm::Value *Size = EmitScalarExpr(size);
  1586. // C11 6.7.6.2p5:
  1587. // If the size is an expression that is not an integer constant
  1588. // expression [...] each time it is evaluated it shall have a value
  1589. // greater than zero.
  1590. if (SanOpts.has(SanitizerKind::VLABound) &&
  1591. size->getType()->isSignedIntegerType()) {
  1592. SanitizerScope SanScope(this);
  1593. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1594. llvm::Constant *StaticArgs[] = {
  1595. EmitCheckSourceLocation(size->getLocStart()),
  1596. EmitCheckTypeDescriptor(size->getType())
  1597. };
  1598. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1599. SanitizerKind::VLABound),
  1600. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1601. }
  1602. // Always zexting here would be wrong if it weren't
  1603. // undefined behavior to have a negative bound.
  1604. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1605. }
  1606. }
  1607. type = vat->getElementType();
  1608. break;
  1609. }
  1610. case Type::FunctionProto:
  1611. case Type::FunctionNoProto:
  1612. type = cast<FunctionType>(ty)->getReturnType();
  1613. break;
  1614. case Type::Paren:
  1615. case Type::TypeOf:
  1616. case Type::UnaryTransform:
  1617. case Type::Attributed:
  1618. case Type::SubstTemplateTypeParm:
  1619. case Type::PackExpansion:
  1620. // Keep walking after single level desugaring.
  1621. type = type.getSingleStepDesugaredType(getContext());
  1622. break;
  1623. case Type::Typedef:
  1624. case Type::Decltype:
  1625. case Type::Auto:
  1626. // Stop walking: nothing to do.
  1627. return;
  1628. case Type::TypeOfExpr:
  1629. // Stop walking: emit typeof expression.
  1630. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1631. return;
  1632. case Type::Atomic:
  1633. type = cast<AtomicType>(ty)->getValueType();
  1634. break;
  1635. case Type::Pipe:
  1636. type = cast<PipeType>(ty)->getElementType();
  1637. break;
  1638. }
  1639. } while (type->isVariablyModifiedType());
  1640. }
  1641. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1642. if (getContext().getBuiltinVaListType()->isArrayType())
  1643. return EmitPointerWithAlignment(E);
  1644. return EmitLValue(E).getAddress();
  1645. }
  1646. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1647. return EmitLValue(E).getAddress();
  1648. }
  1649. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1650. const APValue &Init) {
  1651. assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
  1652. if (CGDebugInfo *Dbg = getDebugInfo())
  1653. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1654. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1655. }
  1656. CodeGenFunction::PeepholeProtection
  1657. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1658. // At the moment, the only aggressive peephole we do in IR gen
  1659. // is trunc(zext) folding, but if we add more, we can easily
  1660. // extend this protection.
  1661. if (!rvalue.isScalar()) return PeepholeProtection();
  1662. llvm::Value *value = rvalue.getScalarVal();
  1663. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1664. // Just make an extra bitcast.
  1665. assert(HaveInsertPoint());
  1666. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1667. Builder.GetInsertBlock());
  1668. PeepholeProtection protection;
  1669. protection.Inst = inst;
  1670. return protection;
  1671. }
  1672. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1673. if (!protection.Inst) return;
  1674. // In theory, we could try to duplicate the peepholes now, but whatever.
  1675. protection.Inst->eraseFromParent();
  1676. }
  1677. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1678. llvm::Value *AnnotatedVal,
  1679. StringRef AnnotationStr,
  1680. SourceLocation Location) {
  1681. llvm::Value *Args[4] = {
  1682. AnnotatedVal,
  1683. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1684. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1685. CGM.EmitAnnotationLineNo(Location)
  1686. };
  1687. return Builder.CreateCall(AnnotationFn, Args);
  1688. }
  1689. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1690. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1691. // FIXME We create a new bitcast for every annotation because that's what
  1692. // llvm-gcc was doing.
  1693. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1694. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1695. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1696. I->getAnnotation(), D->getLocation());
  1697. }
  1698. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1699. Address Addr) {
  1700. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1701. llvm::Value *V = Addr.getPointer();
  1702. llvm::Type *VTy = V->getType();
  1703. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1704. CGM.Int8PtrTy);
  1705. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1706. // FIXME Always emit the cast inst so we can differentiate between
  1707. // annotation on the first field of a struct and annotation on the struct
  1708. // itself.
  1709. if (VTy != CGM.Int8PtrTy)
  1710. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1711. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1712. V = Builder.CreateBitCast(V, VTy);
  1713. }
  1714. return Address(V, Addr.getAlignment());
  1715. }
  1716. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1717. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1718. : CGF(CGF) {
  1719. assert(!CGF->IsSanitizerScope);
  1720. CGF->IsSanitizerScope = true;
  1721. }
  1722. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1723. CGF->IsSanitizerScope = false;
  1724. }
  1725. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1726. const llvm::Twine &Name,
  1727. llvm::BasicBlock *BB,
  1728. llvm::BasicBlock::iterator InsertPt) const {
  1729. LoopStack.InsertHelper(I);
  1730. if (IsSanitizerScope)
  1731. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1732. }
  1733. void CGBuilderInserter::InsertHelper(
  1734. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1735. llvm::BasicBlock::iterator InsertPt) const {
  1736. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1737. if (CGF)
  1738. CGF->InsertHelper(I, Name, BB, InsertPt);
  1739. }
  1740. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1741. CodeGenModule &CGM, const FunctionDecl *FD,
  1742. std::string &FirstMissing) {
  1743. // If there aren't any required features listed then go ahead and return.
  1744. if (ReqFeatures.empty())
  1745. return false;
  1746. // Now build up the set of caller features and verify that all the required
  1747. // features are there.
  1748. llvm::StringMap<bool> CallerFeatureMap;
  1749. CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
  1750. // If we have at least one of the features in the feature list return
  1751. // true, otherwise return false.
  1752. return std::all_of(
  1753. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1754. SmallVector<StringRef, 1> OrFeatures;
  1755. Feature.split(OrFeatures, "|");
  1756. return std::any_of(OrFeatures.begin(), OrFeatures.end(),
  1757. [&](StringRef Feature) {
  1758. if (!CallerFeatureMap.lookup(Feature)) {
  1759. FirstMissing = Feature.str();
  1760. return false;
  1761. }
  1762. return true;
  1763. });
  1764. });
  1765. }
  1766. // Emits an error if we don't have a valid set of target features for the
  1767. // called function.
  1768. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1769. const FunctionDecl *TargetDecl) {
  1770. // Early exit if this is an indirect call.
  1771. if (!TargetDecl)
  1772. return;
  1773. // Get the current enclosing function if it exists. If it doesn't
  1774. // we can't check the target features anyhow.
  1775. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1776. if (!FD)
  1777. return;
  1778. // Grab the required features for the call. For a builtin this is listed in
  1779. // the td file with the default cpu, for an always_inline function this is any
  1780. // listed cpu and any listed features.
  1781. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1782. std::string MissingFeature;
  1783. if (BuiltinID) {
  1784. SmallVector<StringRef, 1> ReqFeatures;
  1785. const char *FeatureList =
  1786. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1787. // Return if the builtin doesn't have any required features.
  1788. if (!FeatureList || StringRef(FeatureList) == "")
  1789. return;
  1790. StringRef(FeatureList).split(ReqFeatures, ",");
  1791. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1792. CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
  1793. << TargetDecl->getDeclName()
  1794. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1795. } else if (TargetDecl->hasAttr<TargetAttr>()) {
  1796. // Get the required features for the callee.
  1797. SmallVector<StringRef, 1> ReqFeatures;
  1798. llvm::StringMap<bool> CalleeFeatureMap;
  1799. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1800. for (const auto &F : CalleeFeatureMap) {
  1801. // Only positive features are "required".
  1802. if (F.getValue())
  1803. ReqFeatures.push_back(F.getKey());
  1804. }
  1805. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1806. CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
  1807. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1808. }
  1809. }
  1810. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1811. if (!CGM.getCodeGenOpts().SanitizeStats)
  1812. return;
  1813. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1814. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1815. CGM.getSanStats().create(IRB, SSK);
  1816. }
  1817. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  1818. if (CGDebugInfo *DI = getDebugInfo())
  1819. return DI->SourceLocToDebugLoc(Location);
  1820. return llvm::DebugLoc();
  1821. }