CodeGenFunction.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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 "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "clang/Frontend/CodeGenOptions.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/MDBuilder.h"
  32. #include "llvm/IR/Operator.h"
  33. using namespace clang;
  34. using namespace CodeGen;
  35. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  36. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  37. Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
  38. CGBuilderInserterTy(this)),
  39. CurFn(nullptr), CapturedStmtInfo(nullptr),
  40. SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
  41. CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
  42. IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr),
  43. LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
  44. NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
  45. ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
  46. AbnormalTerminationSlot(nullptr), SEHPointersDecl(nullptr),
  47. DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
  48. DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
  49. SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
  50. UnreachableBlock(nullptr), NumReturnExprs(0), NumSimpleReturnExprs(0),
  51. CXXABIThisDecl(nullptr), CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  52. CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
  53. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  54. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  55. TerminateHandler(nullptr), TrapBB(nullptr) {
  56. if (!suppressNewContext)
  57. CGM.getCXXABI().getMangleContext().startNewFunction();
  58. llvm::FastMathFlags FMF;
  59. if (CGM.getLangOpts().FastMath)
  60. FMF.setUnsafeAlgebra();
  61. if (CGM.getLangOpts().FiniteMathOnly) {
  62. FMF.setNoNaNs();
  63. FMF.setNoInfs();
  64. }
  65. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  66. FMF.setNoNaNs();
  67. }
  68. if (CGM.getCodeGenOpts().NoSignedZeros) {
  69. FMF.setNoSignedZeros();
  70. }
  71. if (CGM.getCodeGenOpts().ReciprocalMath) {
  72. FMF.setAllowReciprocal();
  73. }
  74. Builder.SetFastMathFlags(FMF);
  75. }
  76. CodeGenFunction::~CodeGenFunction() {
  77. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  78. // If there are any unclaimed block infos, go ahead and destroy them
  79. // now. This can happen if IR-gen gets clever and skips evaluating
  80. // something.
  81. if (FirstBlockInfo)
  82. destroyBlockInfos(FirstBlockInfo);
  83. if (getLangOpts().OpenMP) {
  84. CGM.getOpenMPRuntime().functionFinished(*this);
  85. }
  86. }
  87. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  88. CharUnits Alignment;
  89. if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
  90. Alignment = getContext().getTypeAlignInChars(T);
  91. unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
  92. if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
  93. !getContext().isAlignmentRequired(T))
  94. Alignment = CharUnits::fromQuantity(MaxAlign);
  95. }
  96. return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
  97. }
  98. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  99. return CGM.getTypes().ConvertTypeForMem(T);
  100. }
  101. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  102. return CGM.getTypes().ConvertType(T);
  103. }
  104. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  105. type = type.getCanonicalType();
  106. while (true) {
  107. switch (type->getTypeClass()) {
  108. #define TYPE(name, parent)
  109. #define ABSTRACT_TYPE(name, parent)
  110. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  111. #define DEPENDENT_TYPE(name, parent) case Type::name:
  112. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  113. #include "clang/AST/TypeNodes.def"
  114. llvm_unreachable("non-canonical or dependent type in IR-generation");
  115. case Type::Auto:
  116. llvm_unreachable("undeduced auto type in IR-generation");
  117. // Various scalar types.
  118. case Type::Builtin:
  119. case Type::Pointer:
  120. case Type::BlockPointer:
  121. case Type::LValueReference:
  122. case Type::RValueReference:
  123. case Type::MemberPointer:
  124. case Type::Vector:
  125. case Type::ExtVector:
  126. case Type::FunctionProto:
  127. case Type::FunctionNoProto:
  128. case Type::Enum:
  129. case Type::ObjCObjectPointer:
  130. return TEK_Scalar;
  131. // Complexes.
  132. case Type::Complex:
  133. return TEK_Complex;
  134. // Arrays, records, and Objective-C objects.
  135. case Type::ConstantArray:
  136. case Type::IncompleteArray:
  137. case Type::VariableArray:
  138. case Type::Record:
  139. case Type::ObjCObject:
  140. case Type::ObjCInterface:
  141. return TEK_Aggregate;
  142. // We operate on atomic values according to their underlying type.
  143. case Type::Atomic:
  144. type = cast<AtomicType>(type)->getValueType();
  145. continue;
  146. }
  147. llvm_unreachable("unknown type kind!");
  148. }
  149. }
  150. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  151. // For cleanliness, we try to avoid emitting the return block for
  152. // simple cases.
  153. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  154. if (CurBB) {
  155. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  156. // We have a valid insert point, reuse it if it is empty or there are no
  157. // explicit jumps to the return block.
  158. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  159. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  160. delete ReturnBlock.getBlock();
  161. } else
  162. EmitBlock(ReturnBlock.getBlock());
  163. return llvm::DebugLoc();
  164. }
  165. // Otherwise, if the return block is the target of a single direct
  166. // branch then we can just put the code in that block instead. This
  167. // cleans up functions which started with a unified return block.
  168. if (ReturnBlock.getBlock()->hasOneUse()) {
  169. llvm::BranchInst *BI =
  170. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  171. if (BI && BI->isUnconditional() &&
  172. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  173. // Record/return the DebugLoc of the simple 'return' expression to be used
  174. // later by the actual 'ret' instruction.
  175. llvm::DebugLoc Loc = BI->getDebugLoc();
  176. Builder.SetInsertPoint(BI->getParent());
  177. BI->eraseFromParent();
  178. delete ReturnBlock.getBlock();
  179. return Loc;
  180. }
  181. }
  182. // FIXME: We are at an unreachable point, there is no reason to emit the block
  183. // unless it has uses. However, we still need a place to put the debug
  184. // region.end for now.
  185. EmitBlock(ReturnBlock.getBlock());
  186. return llvm::DebugLoc();
  187. }
  188. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  189. if (!BB) return;
  190. if (!BB->use_empty())
  191. return CGF.CurFn->getBasicBlockList().push_back(BB);
  192. delete BB;
  193. }
  194. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  195. assert(BreakContinueStack.empty() &&
  196. "mismatched push/pop in break/continue stack!");
  197. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  198. && NumSimpleReturnExprs == NumReturnExprs
  199. && ReturnBlock.getBlock()->use_empty();
  200. // Usually the return expression is evaluated before the cleanup
  201. // code. If the function contains only a simple return statement,
  202. // such as a constant, the location before the cleanup code becomes
  203. // the last useful breakpoint in the function, because the simple
  204. // return expression will be evaluated after the cleanup code. To be
  205. // safe, set the debug location for cleanup code to the location of
  206. // the return statement. Otherwise the cleanup code should be at the
  207. // end of the function's lexical scope.
  208. //
  209. // If there are multiple branches to the return block, the branch
  210. // instructions will get the location of the return statements and
  211. // all will be fine.
  212. if (CGDebugInfo *DI = getDebugInfo()) {
  213. if (OnlySimpleReturnStmts)
  214. DI->EmitLocation(Builder, LastStopPoint);
  215. else
  216. DI->EmitLocation(Builder, EndLoc);
  217. }
  218. // Pop any cleanups that might have been associated with the
  219. // parameters. Do this in whatever block we're currently in; it's
  220. // important to do this before we enter the return block or return
  221. // edges will be *really* confused.
  222. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  223. bool HasOnlyLifetimeMarkers =
  224. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  225. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  226. if (HasCleanups) {
  227. // Make sure the line table doesn't jump back into the body for
  228. // the ret after it's been at EndLoc.
  229. if (CGDebugInfo *DI = getDebugInfo())
  230. if (OnlySimpleReturnStmts)
  231. DI->EmitLocation(Builder, EndLoc);
  232. PopCleanupBlocks(PrologueCleanupDepth);
  233. }
  234. // Emit function epilog (to return).
  235. llvm::DebugLoc Loc = EmitReturnBlock();
  236. if (ShouldInstrumentFunction())
  237. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  238. // Emit debug descriptor for function end.
  239. if (CGDebugInfo *DI = getDebugInfo())
  240. DI->EmitFunctionEnd(Builder);
  241. // Reset the debug location to that of the simple 'return' expression, if any
  242. // rather than that of the end of the function's scope '}'.
  243. ApplyDebugLocation AL(*this, Loc);
  244. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  245. EmitEndEHSpec(CurCodeDecl);
  246. assert(EHStack.empty() &&
  247. "did not remove all scopes from cleanup stack!");
  248. // If someone did an indirect goto, emit the indirect goto block at the end of
  249. // the function.
  250. if (IndirectBranch) {
  251. EmitBlock(IndirectBranch->getParent());
  252. Builder.ClearInsertionPoint();
  253. }
  254. // If some of our locals escaped, insert a call to llvm.frameescape in the
  255. // entry block.
  256. if (!EscapedLocals.empty()) {
  257. // Invert the map from local to index into a simple vector. There should be
  258. // no holes.
  259. SmallVector<llvm::Value *, 4> EscapeArgs;
  260. EscapeArgs.resize(EscapedLocals.size());
  261. for (auto &Pair : EscapedLocals)
  262. EscapeArgs[Pair.second] = Pair.first;
  263. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  264. &CGM.getModule(), llvm::Intrinsic::frameescape);
  265. CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  266. }
  267. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  268. llvm::Instruction *Ptr = AllocaInsertPt;
  269. AllocaInsertPt = nullptr;
  270. Ptr->eraseFromParent();
  271. // If someone took the address of a label but never did an indirect goto, we
  272. // made a zero entry PHI node, which is illegal, zap it now.
  273. if (IndirectBranch) {
  274. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  275. if (PN->getNumIncomingValues() == 0) {
  276. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  277. PN->eraseFromParent();
  278. }
  279. }
  280. EmitIfUsed(*this, EHResumeBlock);
  281. EmitIfUsed(*this, TerminateLandingPad);
  282. EmitIfUsed(*this, TerminateHandler);
  283. EmitIfUsed(*this, UnreachableBlock);
  284. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  285. EmitDeclMetadata();
  286. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  287. I = DeferredReplacements.begin(),
  288. E = DeferredReplacements.end();
  289. I != E; ++I) {
  290. I->first->replaceAllUsesWith(I->second);
  291. I->first->eraseFromParent();
  292. }
  293. }
  294. /// ShouldInstrumentFunction - Return true if the current function should be
  295. /// instrumented with __cyg_profile_func_* calls
  296. bool CodeGenFunction::ShouldInstrumentFunction() {
  297. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  298. return false;
  299. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  300. return false;
  301. return true;
  302. }
  303. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  304. /// instrumentation function with the current function and the call site, if
  305. /// function instrumentation is enabled.
  306. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  307. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  308. llvm::PointerType *PointerTy = Int8PtrTy;
  309. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  310. llvm::FunctionType *FunctionTy =
  311. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  312. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  313. llvm::CallInst *CallSite = Builder.CreateCall(
  314. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  315. llvm::ConstantInt::get(Int32Ty, 0),
  316. "callsite");
  317. llvm::Value *args[] = {
  318. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  319. CallSite
  320. };
  321. EmitNounwindRuntimeCall(F, args);
  322. }
  323. void CodeGenFunction::EmitMCountInstrumentation() {
  324. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  325. llvm::Constant *MCountFn =
  326. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  327. EmitNounwindRuntimeCall(MCountFn);
  328. }
  329. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  330. // information in the program executable. The argument information stored
  331. // includes the argument name, its type, the address and access qualifiers used.
  332. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  333. CodeGenModule &CGM, llvm::LLVMContext &Context,
  334. SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
  335. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  336. // Create MDNodes that represent the kernel arg metadata.
  337. // Each MDNode is a list in the form of "key", N number of values which is
  338. // the same number of values as their are kernel arguments.
  339. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  340. // MDNode for the kernel argument address space qualifiers.
  341. SmallVector<llvm::Metadata *, 8> addressQuals;
  342. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  343. // MDNode for the kernel argument access qualifiers (images only).
  344. SmallVector<llvm::Metadata *, 8> accessQuals;
  345. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  346. // MDNode for the kernel argument type names.
  347. SmallVector<llvm::Metadata *, 8> argTypeNames;
  348. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  349. // MDNode for the kernel argument base type names.
  350. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  351. argBaseTypeNames.push_back(
  352. llvm::MDString::get(Context, "kernel_arg_base_type"));
  353. // MDNode for the kernel argument type qualifiers.
  354. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  355. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  356. // MDNode for the kernel argument names.
  357. SmallVector<llvm::Metadata *, 8> argNames;
  358. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  359. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  360. const ParmVarDecl *parm = FD->getParamDecl(i);
  361. QualType ty = parm->getType();
  362. std::string typeQuals;
  363. if (ty->isPointerType()) {
  364. QualType pointeeTy = ty->getPointeeType();
  365. // Get address qualifier.
  366. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  367. ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
  368. // Get argument type name.
  369. std::string typeName =
  370. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  371. // Turn "unsigned type" to "utype"
  372. std::string::size_type pos = typeName.find("unsigned");
  373. if (pointeeTy.isCanonical() && pos != std::string::npos)
  374. typeName.erase(pos+1, 8);
  375. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  376. std::string baseTypeName =
  377. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  378. Policy) +
  379. "*";
  380. // Turn "unsigned type" to "utype"
  381. pos = baseTypeName.find("unsigned");
  382. if (pos != std::string::npos)
  383. baseTypeName.erase(pos+1, 8);
  384. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  385. // Get argument type qualifiers:
  386. if (ty.isRestrictQualified())
  387. typeQuals = "restrict";
  388. if (pointeeTy.isConstQualified() ||
  389. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  390. typeQuals += typeQuals.empty() ? "const" : " const";
  391. if (pointeeTy.isVolatileQualified())
  392. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  393. } else {
  394. uint32_t AddrSpc = 0;
  395. if (ty->isImageType())
  396. AddrSpc =
  397. CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
  398. addressQuals.push_back(
  399. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  400. // Get argument type name.
  401. std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
  402. // Turn "unsigned type" to "utype"
  403. std::string::size_type pos = typeName.find("unsigned");
  404. if (ty.isCanonical() && pos != std::string::npos)
  405. typeName.erase(pos+1, 8);
  406. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  407. std::string baseTypeName =
  408. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  409. // Turn "unsigned type" to "utype"
  410. pos = baseTypeName.find("unsigned");
  411. if (pos != std::string::npos)
  412. baseTypeName.erase(pos+1, 8);
  413. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  414. // Get argument type qualifiers:
  415. if (ty.isConstQualified())
  416. typeQuals = "const";
  417. if (ty.isVolatileQualified())
  418. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  419. }
  420. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  421. // Get image access qualifier:
  422. if (ty->isImageType()) {
  423. const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
  424. if (A && A->isWriteOnly())
  425. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  426. else
  427. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  428. // FIXME: what about read_write?
  429. } else
  430. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  431. // Get argument name.
  432. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  433. }
  434. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  435. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  436. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  437. kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
  438. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  439. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  440. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  441. }
  442. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  443. llvm::Function *Fn)
  444. {
  445. if (!FD->hasAttr<OpenCLKernelAttr>())
  446. return;
  447. llvm::LLVMContext &Context = getLLVMContext();
  448. SmallVector<llvm::Metadata *, 5> kernelMDArgs;
  449. kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
  450. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
  451. getContext());
  452. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  453. QualType hintQTy = A->getTypeHint();
  454. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  455. bool isSignedInteger =
  456. hintQTy->isSignedIntegerType() ||
  457. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  458. llvm::Metadata *attrMDArgs[] = {
  459. llvm::MDString::get(Context, "vec_type_hint"),
  460. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  461. CGM.getTypes().ConvertType(A->getTypeHint()))),
  462. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  463. llvm::IntegerType::get(Context, 32),
  464. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
  465. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  466. }
  467. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  468. llvm::Metadata *attrMDArgs[] = {
  469. llvm::MDString::get(Context, "work_group_size_hint"),
  470. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  471. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  472. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  473. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  474. }
  475. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  476. llvm::Metadata *attrMDArgs[] = {
  477. llvm::MDString::get(Context, "reqd_work_group_size"),
  478. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  479. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  480. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  481. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  482. }
  483. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  484. llvm::NamedMDNode *OpenCLKernelMetadata =
  485. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  486. OpenCLKernelMetadata->addOperand(kernelMDNode);
  487. }
  488. /// Determine whether the function F ends with a return stmt.
  489. static bool endsWithReturn(const Decl* F) {
  490. const Stmt *Body = nullptr;
  491. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  492. Body = FD->getBody();
  493. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  494. Body = OMD->getBody();
  495. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  496. auto LastStmt = CS->body_rbegin();
  497. if (LastStmt != CS->body_rend())
  498. return isa<ReturnStmt>(*LastStmt);
  499. }
  500. return false;
  501. }
  502. void CodeGenFunction::StartFunction(GlobalDecl GD,
  503. QualType RetTy,
  504. llvm::Function *Fn,
  505. const CGFunctionInfo &FnInfo,
  506. const FunctionArgList &Args,
  507. SourceLocation Loc,
  508. SourceLocation StartLoc) {
  509. assert(!CurFn &&
  510. "Do not use a CodeGenFunction object for more than one function");
  511. const Decl *D = GD.getDecl();
  512. DidCallStackSave = false;
  513. CurCodeDecl = D;
  514. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  515. FnRetTy = RetTy;
  516. CurFn = Fn;
  517. CurFnInfo = &FnInfo;
  518. assert(CurFn->isDeclaration() && "Function already has body?");
  519. if (CGM.isInSanitizerBlacklist(Fn, Loc))
  520. SanOpts.clear();
  521. // Pass inline keyword to optimizer if it appears explicitly on any
  522. // declaration. Also, in the case of -fno-inline attach NoInline
  523. // attribute to all function that are not marked AlwaysInline.
  524. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  525. if (!CGM.getCodeGenOpts().NoInline) {
  526. for (auto RI : FD->redecls())
  527. if (RI->isInlineSpecified()) {
  528. Fn->addFnAttr(llvm::Attribute::InlineHint);
  529. break;
  530. }
  531. } else if (!FD->hasAttr<AlwaysInlineAttr>())
  532. Fn->addFnAttr(llvm::Attribute::NoInline);
  533. }
  534. if (getLangOpts().OpenCL) {
  535. // Add metadata for a kernel function.
  536. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  537. EmitOpenCLKernelMetadata(FD, Fn);
  538. }
  539. // If we are checking function types, emit a function type signature as
  540. // prologue data.
  541. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  542. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  543. if (llvm::Constant *PrologueSig =
  544. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  545. llvm::Constant *FTRTTIConst =
  546. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  547. llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
  548. llvm::Constant *PrologueStructConst =
  549. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  550. Fn->setPrologueData(PrologueStructConst);
  551. }
  552. }
  553. }
  554. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  555. // Create a marker to make it easy to insert allocas into the entryblock
  556. // later. Don't create this with the builder, because we don't want it
  557. // folded.
  558. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  559. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  560. if (Builder.isNamePreserving())
  561. AllocaInsertPt->setName("allocapt");
  562. ReturnBlock = getJumpDestInCurrentScope("return");
  563. Builder.SetInsertPoint(EntryBB);
  564. // Emit subprogram debug descriptor.
  565. if (CGDebugInfo *DI = getDebugInfo()) {
  566. SmallVector<QualType, 16> ArgTypes;
  567. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  568. i != e; ++i) {
  569. ArgTypes.push_back((*i)->getType());
  570. }
  571. QualType FnType =
  572. getContext().getFunctionType(RetTy, ArgTypes,
  573. FunctionProtoType::ExtProtoInfo());
  574. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  575. }
  576. if (ShouldInstrumentFunction())
  577. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  578. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  579. EmitMCountInstrumentation();
  580. if (RetTy->isVoidType()) {
  581. // Void type; nothing to return.
  582. ReturnValue = nullptr;
  583. // Count the implicit return.
  584. if (!endsWithReturn(D))
  585. ++NumReturnExprs;
  586. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  587. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  588. // Indirect aggregate return; emit returned value directly into sret slot.
  589. // This reduces code size, and affects correctness in C++.
  590. auto AI = CurFn->arg_begin();
  591. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  592. ++AI;
  593. ReturnValue = AI;
  594. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  595. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  596. // Load the sret pointer from the argument struct and return into that.
  597. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  598. llvm::Function::arg_iterator EI = CurFn->arg_end();
  599. --EI;
  600. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
  601. ReturnValue = Builder.CreateLoad(Addr, "agg.result");
  602. } else {
  603. ReturnValue = CreateIRTemp(RetTy, "retval");
  604. // Tell the epilog emitter to autorelease the result. We do this
  605. // now so that various specialized functions can suppress it
  606. // during their IR-generation.
  607. if (getLangOpts().ObjCAutoRefCount &&
  608. !CurFnInfo->isReturnsRetained() &&
  609. RetTy->isObjCRetainableType())
  610. AutoreleaseResult = true;
  611. }
  612. EmitStartEHSpec(CurCodeDecl);
  613. PrologueCleanupDepth = EHStack.stable_begin();
  614. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  615. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  616. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  617. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  618. if (MD->getParent()->isLambda() &&
  619. MD->getOverloadedOperator() == OO_Call) {
  620. // We're in a lambda; figure out the captures.
  621. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  622. LambdaThisCaptureField);
  623. if (LambdaThisCaptureField) {
  624. // If this lambda captures this, load it.
  625. LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  626. CXXThisValue = EmitLoadOfLValue(ThisLValue,
  627. SourceLocation()).getScalarVal();
  628. }
  629. for (auto *FD : MD->getParent()->fields()) {
  630. if (FD->hasCapturedVLAType()) {
  631. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  632. SourceLocation()).getScalarVal();
  633. auto VAT = FD->getCapturedVLAType();
  634. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  635. }
  636. }
  637. } else {
  638. // Not in a lambda; just use 'this' from the method.
  639. // FIXME: Should we generate a new load for each use of 'this'? The
  640. // fast register allocator would be happier...
  641. CXXThisValue = CXXABIThisValue;
  642. }
  643. }
  644. // If any of the arguments have a variably modified type, make sure to
  645. // emit the type size.
  646. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  647. i != e; ++i) {
  648. const VarDecl *VD = *i;
  649. // Dig out the type as written from ParmVarDecls; it's unclear whether
  650. // the standard (C99 6.9.1p10) requires this, but we're following the
  651. // precedent set by gcc.
  652. QualType Ty;
  653. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  654. Ty = PVD->getOriginalType();
  655. else
  656. Ty = VD->getType();
  657. if (Ty->isVariablyModifiedType())
  658. EmitVariablyModifiedType(Ty);
  659. }
  660. // Emit a location at the end of the prologue.
  661. if (CGDebugInfo *DI = getDebugInfo())
  662. DI->EmitLocation(Builder, StartLoc);
  663. }
  664. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  665. const Stmt *Body) {
  666. incrementProfileCounter(Body);
  667. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  668. EmitCompoundStmtWithoutScope(*S);
  669. else
  670. EmitStmt(Body);
  671. }
  672. /// When instrumenting to collect profile data, the counts for some blocks
  673. /// such as switch cases need to not include the fall-through counts, so
  674. /// emit a branch around the instrumentation code. When not instrumenting,
  675. /// this just calls EmitBlock().
  676. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  677. const Stmt *S) {
  678. llvm::BasicBlock *SkipCountBB = nullptr;
  679. if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
  680. // When instrumenting for profiling, the fallthrough to certain
  681. // statements needs to skip over the instrumentation code so that we
  682. // get an accurate count.
  683. SkipCountBB = createBasicBlock("skipcount");
  684. EmitBranch(SkipCountBB);
  685. }
  686. EmitBlock(BB);
  687. uint64_t CurrentCount = getCurrentProfileCount();
  688. incrementProfileCounter(S);
  689. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  690. if (SkipCountBB)
  691. EmitBlock(SkipCountBB);
  692. }
  693. /// Tries to mark the given function nounwind based on the
  694. /// non-existence of any throwing calls within it. We believe this is
  695. /// lightweight enough to do at -O0.
  696. static void TryMarkNoThrow(llvm::Function *F) {
  697. // LLVM treats 'nounwind' on a function as part of the type, so we
  698. // can't do this on functions that can be overwritten.
  699. if (F->mayBeOverridden()) return;
  700. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  701. for (llvm::BasicBlock::iterator
  702. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  703. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  704. if (!Call->doesNotThrow())
  705. return;
  706. } else if (isa<llvm::ResumeInst>(&*BI)) {
  707. return;
  708. }
  709. F->setDoesNotThrow();
  710. }
  711. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  712. const CGFunctionInfo &FnInfo) {
  713. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  714. // Check if we should generate debug info for this function.
  715. if (FD->hasAttr<NoDebugAttr>())
  716. DebugInfo = nullptr; // disable debug info indefinitely for this function
  717. FunctionArgList Args;
  718. QualType ResTy = FD->getReturnType();
  719. CurGD = GD;
  720. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  721. if (MD && MD->isInstance()) {
  722. if (CGM.getCXXABI().HasThisReturn(GD))
  723. ResTy = MD->getThisType(getContext());
  724. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  725. ResTy = CGM.getContext().VoidPtrTy;
  726. CGM.getCXXABI().buildThisParam(*this, Args);
  727. }
  728. Args.append(FD->param_begin(), FD->param_end());
  729. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  730. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  731. SourceRange BodyRange;
  732. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  733. CurEHLocation = BodyRange.getEnd();
  734. // Use the location of the start of the function to determine where
  735. // the function definition is located. By default use the location
  736. // of the declaration as the location for the subprogram. A function
  737. // may lack a declaration in the source code if it is created by code
  738. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  739. SourceLocation Loc = FD->getLocation();
  740. // If this is a function specialization then use the pattern body
  741. // as the location for the function.
  742. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  743. if (SpecDecl->hasBody(SpecDecl))
  744. Loc = SpecDecl->getLocation();
  745. // Emit the standard function prologue.
  746. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  747. // Generate the body of the function.
  748. PGO.checkGlobalDecl(GD);
  749. PGO.assignRegionCounters(GD.getDecl(), CurFn);
  750. if (isa<CXXDestructorDecl>(FD))
  751. EmitDestructorBody(Args);
  752. else if (isa<CXXConstructorDecl>(FD))
  753. EmitConstructorBody(Args);
  754. else if (getLangOpts().CUDA &&
  755. !getLangOpts().CUDAIsDevice &&
  756. FD->hasAttr<CUDAGlobalAttr>())
  757. CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
  758. else if (isa<CXXConversionDecl>(FD) &&
  759. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  760. // The lambda conversion to block pointer is special; the semantics can't be
  761. // expressed in the AST, so IRGen needs to special-case it.
  762. EmitLambdaToBlockPointerBody(Args);
  763. } else if (isa<CXXMethodDecl>(FD) &&
  764. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  765. // The lambda static invoker function is special, because it forwards or
  766. // clones the body of the function call operator (but is actually static).
  767. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  768. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  769. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  770. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  771. // Implicit copy-assignment gets the same special treatment as implicit
  772. // copy-constructors.
  773. emitImplicitAssignmentOperatorBody(Args);
  774. } else if (Stmt *Body = FD->getBody()) {
  775. EmitFunctionBody(Args, Body);
  776. } else
  777. llvm_unreachable("no definition for emitted function");
  778. // C++11 [stmt.return]p2:
  779. // Flowing off the end of a function [...] results in undefined behavior in
  780. // a value-returning function.
  781. // C11 6.9.1p12:
  782. // If the '}' that terminates a function is reached, and the value of the
  783. // function call is used by the caller, the behavior is undefined.
  784. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  785. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  786. if (SanOpts.has(SanitizerKind::Return)) {
  787. SanitizerScope SanScope(this);
  788. llvm::Value *IsFalse = Builder.getFalse();
  789. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  790. "missing_return", EmitCheckSourceLocation(FD->getLocation()),
  791. None);
  792. } else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  793. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
  794. Builder.CreateUnreachable();
  795. Builder.ClearInsertionPoint();
  796. }
  797. // Emit the standard function epilogue.
  798. FinishFunction(BodyRange.getEnd());
  799. // If we haven't marked the function nothrow through other means, do
  800. // a quick pass now to see if we can.
  801. if (!CurFn->doesNotThrow())
  802. TryMarkNoThrow(CurFn);
  803. }
  804. /// ContainsLabel - Return true if the statement contains a label in it. If
  805. /// this statement is not executed normally, it not containing a label means
  806. /// that we can just remove the code.
  807. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  808. // Null statement, not a label!
  809. if (!S) return false;
  810. // If this is a label, we have to emit the code, consider something like:
  811. // if (0) { ... foo: bar(); } goto foo;
  812. //
  813. // TODO: If anyone cared, we could track __label__'s, since we know that you
  814. // can't jump to one from outside their declared region.
  815. if (isa<LabelStmt>(S))
  816. return true;
  817. // If this is a case/default statement, and we haven't seen a switch, we have
  818. // to emit the code.
  819. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  820. return true;
  821. // If this is a switch statement, we want to ignore cases below it.
  822. if (isa<SwitchStmt>(S))
  823. IgnoreCaseStmts = true;
  824. // Scan subexpressions for verboten labels.
  825. for (Stmt::const_child_range I = S->children(); I; ++I)
  826. if (ContainsLabel(*I, IgnoreCaseStmts))
  827. return true;
  828. return false;
  829. }
  830. /// containsBreak - Return true if the statement contains a break out of it.
  831. /// If the statement (recursively) contains a switch or loop with a break
  832. /// inside of it, this is fine.
  833. bool CodeGenFunction::containsBreak(const Stmt *S) {
  834. // Null statement, not a label!
  835. if (!S) return false;
  836. // If this is a switch or loop that defines its own break scope, then we can
  837. // include it and anything inside of it.
  838. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  839. isa<ForStmt>(S))
  840. return false;
  841. if (isa<BreakStmt>(S))
  842. return true;
  843. // Scan subexpressions for verboten breaks.
  844. for (Stmt::const_child_range I = S->children(); I; ++I)
  845. if (containsBreak(*I))
  846. return true;
  847. return false;
  848. }
  849. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  850. /// to a constant, or if it does but contains a label, return false. If it
  851. /// constant folds return true and set the boolean result in Result.
  852. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  853. bool &ResultBool) {
  854. llvm::APSInt ResultInt;
  855. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  856. return false;
  857. ResultBool = ResultInt.getBoolValue();
  858. return true;
  859. }
  860. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  861. /// to a constant, or if it does but contains a label, return false. If it
  862. /// constant folds return true and set the folded value.
  863. bool CodeGenFunction::
  864. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  865. // FIXME: Rename and handle conversion of other evaluatable things
  866. // to bool.
  867. llvm::APSInt Int;
  868. if (!Cond->EvaluateAsInt(Int, getContext()))
  869. return false; // Not foldable, not integer or not fully evaluatable.
  870. if (CodeGenFunction::ContainsLabel(Cond))
  871. return false; // Contains a label.
  872. ResultInt = Int;
  873. return true;
  874. }
  875. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  876. /// statement) to the specified blocks. Based on the condition, this might try
  877. /// to simplify the codegen of the conditional based on the branch.
  878. ///
  879. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  880. llvm::BasicBlock *TrueBlock,
  881. llvm::BasicBlock *FalseBlock,
  882. uint64_t TrueCount) {
  883. Cond = Cond->IgnoreParens();
  884. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  885. // Handle X && Y in a condition.
  886. if (CondBOp->getOpcode() == BO_LAnd) {
  887. // If we have "1 && X", simplify the code. "0 && X" would have constant
  888. // folded if the case was simple enough.
  889. bool ConstantBool = false;
  890. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  891. ConstantBool) {
  892. // br(1 && X) -> br(X).
  893. incrementProfileCounter(CondBOp);
  894. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  895. TrueCount);
  896. }
  897. // If we have "X && 1", simplify the code to use an uncond branch.
  898. // "X && 0" would have been constant folded to 0.
  899. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  900. ConstantBool) {
  901. // br(X && 1) -> br(X).
  902. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  903. TrueCount);
  904. }
  905. // Emit the LHS as a conditional. If the LHS conditional is false, we
  906. // want to jump to the FalseBlock.
  907. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  908. // The counter tells us how often we evaluate RHS, and all of TrueCount
  909. // can be propagated to that branch.
  910. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  911. ConditionalEvaluation eval(*this);
  912. {
  913. ApplyDebugLocation DL(*this, Cond);
  914. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  915. EmitBlock(LHSTrue);
  916. }
  917. incrementProfileCounter(CondBOp);
  918. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  919. // Any temporaries created here are conditional.
  920. eval.begin(*this);
  921. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  922. eval.end(*this);
  923. return;
  924. }
  925. if (CondBOp->getOpcode() == BO_LOr) {
  926. // If we have "0 || X", simplify the code. "1 || X" would have constant
  927. // folded if the case was simple enough.
  928. bool ConstantBool = false;
  929. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  930. !ConstantBool) {
  931. // br(0 || X) -> br(X).
  932. incrementProfileCounter(CondBOp);
  933. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  934. TrueCount);
  935. }
  936. // If we have "X || 0", simplify the code to use an uncond branch.
  937. // "X || 1" would have been constant folded to 1.
  938. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  939. !ConstantBool) {
  940. // br(X || 0) -> br(X).
  941. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  942. TrueCount);
  943. }
  944. // Emit the LHS as a conditional. If the LHS conditional is true, we
  945. // want to jump to the TrueBlock.
  946. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  947. // We have the count for entry to the RHS and for the whole expression
  948. // being true, so we can divy up True count between the short circuit and
  949. // the RHS.
  950. uint64_t LHSCount =
  951. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  952. uint64_t RHSCount = TrueCount - LHSCount;
  953. ConditionalEvaluation eval(*this);
  954. {
  955. ApplyDebugLocation DL(*this, Cond);
  956. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  957. EmitBlock(LHSFalse);
  958. }
  959. incrementProfileCounter(CondBOp);
  960. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  961. // Any temporaries created here are conditional.
  962. eval.begin(*this);
  963. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  964. eval.end(*this);
  965. return;
  966. }
  967. }
  968. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  969. // br(!x, t, f) -> br(x, f, t)
  970. if (CondUOp->getOpcode() == UO_LNot) {
  971. // Negate the count.
  972. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  973. // Negate the condition and swap the destination blocks.
  974. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  975. FalseCount);
  976. }
  977. }
  978. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  979. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  980. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  981. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  982. ConditionalEvaluation cond(*this);
  983. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  984. getProfileCount(CondOp));
  985. // When computing PGO branch weights, we only know the overall count for
  986. // the true block. This code is essentially doing tail duplication of the
  987. // naive code-gen, introducing new edges for which counts are not
  988. // available. Divide the counts proportionally between the LHS and RHS of
  989. // the conditional operator.
  990. uint64_t LHSScaledTrueCount = 0;
  991. if (TrueCount) {
  992. double LHSRatio =
  993. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  994. LHSScaledTrueCount = TrueCount * LHSRatio;
  995. }
  996. cond.begin(*this);
  997. EmitBlock(LHSBlock);
  998. incrementProfileCounter(CondOp);
  999. {
  1000. ApplyDebugLocation DL(*this, Cond);
  1001. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1002. LHSScaledTrueCount);
  1003. }
  1004. cond.end(*this);
  1005. cond.begin(*this);
  1006. EmitBlock(RHSBlock);
  1007. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1008. TrueCount - LHSScaledTrueCount);
  1009. cond.end(*this);
  1010. return;
  1011. }
  1012. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1013. // Conditional operator handling can give us a throw expression as a
  1014. // condition for a case like:
  1015. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1016. // Fold this to:
  1017. // br(c, throw x, br(y, t, f))
  1018. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1019. return;
  1020. }
  1021. // Create branch weights based on the number of times we get here and the
  1022. // number of times the condition should be true.
  1023. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1024. llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount,
  1025. CurrentCount - TrueCount);
  1026. // Emit the code with the fully general case.
  1027. llvm::Value *CondV;
  1028. {
  1029. ApplyDebugLocation DL(*this, Cond);
  1030. CondV = EvaluateExprAsBool(Cond);
  1031. }
  1032. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
  1033. }
  1034. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1035. /// specified stmt yet.
  1036. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1037. CGM.ErrorUnsupported(S, Type);
  1038. }
  1039. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1040. /// variable-length array whose elements have a non-zero bit-pattern.
  1041. ///
  1042. /// \param baseType the inner-most element type of the array
  1043. /// \param src - a char* pointing to the bit-pattern for a single
  1044. /// base element of the array
  1045. /// \param sizeInChars - the total size of the VLA, in chars
  1046. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1047. llvm::Value *dest, llvm::Value *src,
  1048. llvm::Value *sizeInChars) {
  1049. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  1050. = CGF.getContext().getTypeInfoInChars(baseType);
  1051. CGBuilderTy &Builder = CGF.Builder;
  1052. llvm::Value *baseSizeInChars
  1053. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  1054. llvm::Type *i8p = Builder.getInt8PtrTy();
  1055. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  1056. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  1057. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1058. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1059. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1060. // Make a loop over the VLA. C99 guarantees that the VLA element
  1061. // count must be nonzero.
  1062. CGF.EmitBlock(loopBB);
  1063. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  1064. cur->addIncoming(begin, originBB);
  1065. // memcpy the individual element bit-pattern.
  1066. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  1067. baseSizeAndAlign.second.getQuantity(),
  1068. /*volatile*/ false);
  1069. // Go to the next element.
  1070. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
  1071. cur, 1, "vla.next");
  1072. // Leave if that's the end of the VLA.
  1073. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1074. Builder.CreateCondBr(done, contBB, loopBB);
  1075. cur->addIncoming(next, loopBB);
  1076. CGF.EmitBlock(contBB);
  1077. }
  1078. void
  1079. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  1080. // Ignore empty classes in C++.
  1081. if (getLangOpts().CPlusPlus) {
  1082. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1083. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1084. return;
  1085. }
  1086. }
  1087. // Cast the dest ptr to the appropriate i8 pointer type.
  1088. unsigned DestAS =
  1089. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  1090. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  1091. if (DestPtr->getType() != BP)
  1092. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  1093. // Get size and alignment info for this aggregate.
  1094. std::pair<CharUnits, CharUnits> TypeInfo =
  1095. getContext().getTypeInfoInChars(Ty);
  1096. CharUnits Size = TypeInfo.first;
  1097. CharUnits Align = TypeInfo.second;
  1098. llvm::Value *SizeVal;
  1099. const VariableArrayType *vla;
  1100. // Don't bother emitting a zero-byte memset.
  1101. if (Size.isZero()) {
  1102. // But note that getTypeInfo returns 0 for a VLA.
  1103. if (const VariableArrayType *vlaType =
  1104. dyn_cast_or_null<VariableArrayType>(
  1105. getContext().getAsArrayType(Ty))) {
  1106. QualType eltType;
  1107. llvm::Value *numElts;
  1108. std::tie(numElts, eltType) = getVLASize(vlaType);
  1109. SizeVal = numElts;
  1110. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  1111. if (!eltSize.isOne())
  1112. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1113. vla = vlaType;
  1114. } else {
  1115. return;
  1116. }
  1117. } else {
  1118. SizeVal = CGM.getSize(Size);
  1119. vla = nullptr;
  1120. }
  1121. // If the type contains a pointer to data member we can't memset it to zero.
  1122. // Instead, create a null constant and copy it to the destination.
  1123. // TODO: there are other patterns besides zero that we can usefully memset,
  1124. // like -1, which happens to be the pattern used by member-pointers.
  1125. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1126. // For a VLA, emit a single element, then splat that over the VLA.
  1127. if (vla) Ty = getContext().getBaseElementType(vla);
  1128. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1129. llvm::GlobalVariable *NullVariable =
  1130. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1131. /*isConstant=*/true,
  1132. llvm::GlobalVariable::PrivateLinkage,
  1133. NullConstant, Twine());
  1134. llvm::Value *SrcPtr =
  1135. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  1136. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1137. // Get and call the appropriate llvm.memcpy overload.
  1138. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  1139. return;
  1140. }
  1141. // Otherwise, just memset the whole thing to zero. This is legal
  1142. // because in LLVM, all default initializers (other than the ones we just
  1143. // handled above) are guaranteed to have a bit pattern of all zeros.
  1144. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  1145. Align.getQuantity(), false);
  1146. }
  1147. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1148. // Make sure that there is a block for the indirect goto.
  1149. if (!IndirectBranch)
  1150. GetIndirectGotoBlock();
  1151. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1152. // Make sure the indirect branch includes all of the address-taken blocks.
  1153. IndirectBranch->addDestination(BB);
  1154. return llvm::BlockAddress::get(CurFn, BB);
  1155. }
  1156. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1157. // If we already made the indirect branch for indirect goto, return its block.
  1158. if (IndirectBranch) return IndirectBranch->getParent();
  1159. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  1160. // Create the PHI node that indirect gotos will add entries to.
  1161. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1162. "indirect.goto.dest");
  1163. // Create the indirect branch instruction.
  1164. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1165. return IndirectBranch->getParent();
  1166. }
  1167. /// Computes the length of an array in elements, as well as the base
  1168. /// element type and a properly-typed first element pointer.
  1169. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1170. QualType &baseType,
  1171. llvm::Value *&addr) {
  1172. const ArrayType *arrayType = origArrayType;
  1173. // If it's a VLA, we have to load the stored size. Note that
  1174. // this is the size of the VLA in bytes, not its size in elements.
  1175. llvm::Value *numVLAElements = nullptr;
  1176. if (isa<VariableArrayType>(arrayType)) {
  1177. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  1178. // Walk into all VLAs. This doesn't require changes to addr,
  1179. // which has type T* where T is the first non-VLA element type.
  1180. do {
  1181. QualType elementType = arrayType->getElementType();
  1182. arrayType = getContext().getAsArrayType(elementType);
  1183. // If we only have VLA components, 'addr' requires no adjustment.
  1184. if (!arrayType) {
  1185. baseType = elementType;
  1186. return numVLAElements;
  1187. }
  1188. } while (isa<VariableArrayType>(arrayType));
  1189. // We get out here only if we find a constant array type
  1190. // inside the VLA.
  1191. }
  1192. // We have some number of constant-length arrays, so addr should
  1193. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1194. // down to the first element of addr.
  1195. SmallVector<llvm::Value*, 8> gepIndices;
  1196. // GEP down to the array type.
  1197. llvm::ConstantInt *zero = Builder.getInt32(0);
  1198. gepIndices.push_back(zero);
  1199. uint64_t countFromCLAs = 1;
  1200. QualType eltType;
  1201. llvm::ArrayType *llvmArrayType =
  1202. dyn_cast<llvm::ArrayType>(
  1203. cast<llvm::PointerType>(addr->getType())->getElementType());
  1204. while (llvmArrayType) {
  1205. assert(isa<ConstantArrayType>(arrayType));
  1206. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1207. == llvmArrayType->getNumElements());
  1208. gepIndices.push_back(zero);
  1209. countFromCLAs *= llvmArrayType->getNumElements();
  1210. eltType = arrayType->getElementType();
  1211. llvmArrayType =
  1212. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1213. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1214. assert((!llvmArrayType || arrayType) &&
  1215. "LLVM and Clang types are out-of-synch");
  1216. }
  1217. if (arrayType) {
  1218. // From this point onwards, the Clang array type has been emitted
  1219. // as some other type (probably a packed struct). Compute the array
  1220. // size, and just emit the 'begin' expression as a bitcast.
  1221. while (arrayType) {
  1222. countFromCLAs *=
  1223. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1224. eltType = arrayType->getElementType();
  1225. arrayType = getContext().getAsArrayType(eltType);
  1226. }
  1227. unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
  1228. llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
  1229. addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
  1230. } else {
  1231. // Create the actual GEP.
  1232. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  1233. }
  1234. baseType = eltType;
  1235. llvm::Value *numElements
  1236. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1237. // If we had any VLA dimensions, factor them in.
  1238. if (numVLAElements)
  1239. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1240. return numElements;
  1241. }
  1242. std::pair<llvm::Value*, QualType>
  1243. CodeGenFunction::getVLASize(QualType type) {
  1244. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1245. assert(vla && "type was not a variable array type!");
  1246. return getVLASize(vla);
  1247. }
  1248. std::pair<llvm::Value*, QualType>
  1249. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1250. // The number of elements so far; always size_t.
  1251. llvm::Value *numElements = nullptr;
  1252. QualType elementType;
  1253. do {
  1254. elementType = type->getElementType();
  1255. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1256. assert(vlaSize && "no size for VLA!");
  1257. assert(vlaSize->getType() == SizeTy);
  1258. if (!numElements) {
  1259. numElements = vlaSize;
  1260. } else {
  1261. // It's undefined behavior if this wraps around, so mark it that way.
  1262. // FIXME: Teach -fsanitize=undefined to trap this.
  1263. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1264. }
  1265. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1266. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1267. }
  1268. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1269. assert(type->isVariablyModifiedType() &&
  1270. "Must pass variably modified type to EmitVLASizes!");
  1271. EnsureInsertPoint();
  1272. // We're going to walk down into the type and look for VLA
  1273. // expressions.
  1274. do {
  1275. assert(type->isVariablyModifiedType());
  1276. const Type *ty = type.getTypePtr();
  1277. switch (ty->getTypeClass()) {
  1278. #define TYPE(Class, Base)
  1279. #define ABSTRACT_TYPE(Class, Base)
  1280. #define NON_CANONICAL_TYPE(Class, Base)
  1281. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1282. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1283. #include "clang/AST/TypeNodes.def"
  1284. llvm_unreachable("unexpected dependent type!");
  1285. // These types are never variably-modified.
  1286. case Type::Builtin:
  1287. case Type::Complex:
  1288. case Type::Vector:
  1289. case Type::ExtVector:
  1290. case Type::Record:
  1291. case Type::Enum:
  1292. case Type::Elaborated:
  1293. case Type::TemplateSpecialization:
  1294. case Type::ObjCObject:
  1295. case Type::ObjCInterface:
  1296. case Type::ObjCObjectPointer:
  1297. llvm_unreachable("type class is never variably-modified!");
  1298. case Type::Adjusted:
  1299. type = cast<AdjustedType>(ty)->getAdjustedType();
  1300. break;
  1301. case Type::Decayed:
  1302. type = cast<DecayedType>(ty)->getPointeeType();
  1303. break;
  1304. case Type::Pointer:
  1305. type = cast<PointerType>(ty)->getPointeeType();
  1306. break;
  1307. case Type::BlockPointer:
  1308. type = cast<BlockPointerType>(ty)->getPointeeType();
  1309. break;
  1310. case Type::LValueReference:
  1311. case Type::RValueReference:
  1312. type = cast<ReferenceType>(ty)->getPointeeType();
  1313. break;
  1314. case Type::MemberPointer:
  1315. type = cast<MemberPointerType>(ty)->getPointeeType();
  1316. break;
  1317. case Type::ConstantArray:
  1318. case Type::IncompleteArray:
  1319. // Losing element qualification here is fine.
  1320. type = cast<ArrayType>(ty)->getElementType();
  1321. break;
  1322. case Type::VariableArray: {
  1323. // Losing element qualification here is fine.
  1324. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1325. // Unknown size indication requires no size computation.
  1326. // Otherwise, evaluate and record it.
  1327. if (const Expr *size = vat->getSizeExpr()) {
  1328. // It's possible that we might have emitted this already,
  1329. // e.g. with a typedef and a pointer to it.
  1330. llvm::Value *&entry = VLASizeMap[size];
  1331. if (!entry) {
  1332. llvm::Value *Size = EmitScalarExpr(size);
  1333. // C11 6.7.6.2p5:
  1334. // If the size is an expression that is not an integer constant
  1335. // expression [...] each time it is evaluated it shall have a value
  1336. // greater than zero.
  1337. if (SanOpts.has(SanitizerKind::VLABound) &&
  1338. size->getType()->isSignedIntegerType()) {
  1339. SanitizerScope SanScope(this);
  1340. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1341. llvm::Constant *StaticArgs[] = {
  1342. EmitCheckSourceLocation(size->getLocStart()),
  1343. EmitCheckTypeDescriptor(size->getType())
  1344. };
  1345. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1346. SanitizerKind::VLABound),
  1347. "vla_bound_not_positive", StaticArgs, Size);
  1348. }
  1349. // Always zexting here would be wrong if it weren't
  1350. // undefined behavior to have a negative bound.
  1351. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1352. }
  1353. }
  1354. type = vat->getElementType();
  1355. break;
  1356. }
  1357. case Type::FunctionProto:
  1358. case Type::FunctionNoProto:
  1359. type = cast<FunctionType>(ty)->getReturnType();
  1360. break;
  1361. case Type::Paren:
  1362. case Type::TypeOf:
  1363. case Type::UnaryTransform:
  1364. case Type::Attributed:
  1365. case Type::SubstTemplateTypeParm:
  1366. case Type::PackExpansion:
  1367. // Keep walking after single level desugaring.
  1368. type = type.getSingleStepDesugaredType(getContext());
  1369. break;
  1370. case Type::Typedef:
  1371. case Type::Decltype:
  1372. case Type::Auto:
  1373. // Stop walking: nothing to do.
  1374. return;
  1375. case Type::TypeOfExpr:
  1376. // Stop walking: emit typeof expression.
  1377. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1378. return;
  1379. case Type::Atomic:
  1380. type = cast<AtomicType>(ty)->getValueType();
  1381. break;
  1382. }
  1383. } while (type->isVariablyModifiedType());
  1384. }
  1385. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  1386. if (getContext().getBuiltinVaListType()->isArrayType())
  1387. return EmitScalarExpr(E);
  1388. return EmitLValue(E).getAddress();
  1389. }
  1390. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1391. llvm::Constant *Init) {
  1392. assert (Init && "Invalid DeclRefExpr initializer!");
  1393. if (CGDebugInfo *Dbg = getDebugInfo())
  1394. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1395. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1396. }
  1397. CodeGenFunction::PeepholeProtection
  1398. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1399. // At the moment, the only aggressive peephole we do in IR gen
  1400. // is trunc(zext) folding, but if we add more, we can easily
  1401. // extend this protection.
  1402. if (!rvalue.isScalar()) return PeepholeProtection();
  1403. llvm::Value *value = rvalue.getScalarVal();
  1404. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1405. // Just make an extra bitcast.
  1406. assert(HaveInsertPoint());
  1407. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1408. Builder.GetInsertBlock());
  1409. PeepholeProtection protection;
  1410. protection.Inst = inst;
  1411. return protection;
  1412. }
  1413. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1414. if (!protection.Inst) return;
  1415. // In theory, we could try to duplicate the peepholes now, but whatever.
  1416. protection.Inst->eraseFromParent();
  1417. }
  1418. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1419. llvm::Value *AnnotatedVal,
  1420. StringRef AnnotationStr,
  1421. SourceLocation Location) {
  1422. llvm::Value *Args[4] = {
  1423. AnnotatedVal,
  1424. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1425. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1426. CGM.EmitAnnotationLineNo(Location)
  1427. };
  1428. return Builder.CreateCall(AnnotationFn, Args);
  1429. }
  1430. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1431. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1432. // FIXME We create a new bitcast for every annotation because that's what
  1433. // llvm-gcc was doing.
  1434. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1435. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1436. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1437. I->getAnnotation(), D->getLocation());
  1438. }
  1439. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1440. llvm::Value *V) {
  1441. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1442. llvm::Type *VTy = V->getType();
  1443. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1444. CGM.Int8PtrTy);
  1445. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1446. // FIXME Always emit the cast inst so we can differentiate between
  1447. // annotation on the first field of a struct and annotation on the struct
  1448. // itself.
  1449. if (VTy != CGM.Int8PtrTy)
  1450. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1451. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1452. V = Builder.CreateBitCast(V, VTy);
  1453. }
  1454. return V;
  1455. }
  1456. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1457. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1458. : CGF(CGF) {
  1459. assert(!CGF->IsSanitizerScope);
  1460. CGF->IsSanitizerScope = true;
  1461. }
  1462. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1463. CGF->IsSanitizerScope = false;
  1464. }
  1465. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1466. const llvm::Twine &Name,
  1467. llvm::BasicBlock *BB,
  1468. llvm::BasicBlock::iterator InsertPt) const {
  1469. LoopStack.InsertHelper(I);
  1470. if (IsSanitizerScope)
  1471. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1472. }
  1473. template <bool PreserveNames>
  1474. void CGBuilderInserter<PreserveNames>::InsertHelper(
  1475. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1476. llvm::BasicBlock::iterator InsertPt) const {
  1477. llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
  1478. InsertPt);
  1479. if (CGF)
  1480. CGF->InsertHelper(I, Name, BB, InsertPt);
  1481. }
  1482. #ifdef NDEBUG
  1483. #define PreserveNames false
  1484. #else
  1485. #define PreserveNames true
  1486. #endif
  1487. template void CGBuilderInserter<PreserveNames>::InsertHelper(
  1488. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1489. llvm::BasicBlock::iterator InsertPt) const;
  1490. #undef PreserveNames