clang  8.0.0svn
CGStmt.cpp
Go to the documentation of this file.
1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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 contains code to emit Stmt nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/Builtins.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/MDBuilder.h"
28 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 //===----------------------------------------------------------------------===//
33 // Statement Emission
34 //===----------------------------------------------------------------------===//
35 
37  if (CGDebugInfo *DI = getDebugInfo()) {
38  SourceLocation Loc;
39  Loc = S->getBeginLoc();
40  DI->EmitLocation(Builder, Loc);
41 
42  LastStopPoint = Loc;
43  }
44 }
45 
47  assert(S && "Null statement?");
48  PGO.setCurrentStmt(S);
49 
50  // These statements have their own debug info handling.
51  if (EmitSimpleStmt(S))
52  return;
53 
54  // Check if we are generating unreachable code.
55  if (!HaveInsertPoint()) {
56  // If so, and the statement doesn't contain a label, then we do not need to
57  // generate actual code. This is safe because (1) the current point is
58  // unreachable, so we don't need to execute the code, and (2) we've already
59  // handled the statements which update internal data structures (like the
60  // local variable map) which could be used by subsequent statements.
61  if (!ContainsLabel(S)) {
62  // Verify that any decl statements were handled as simple, they may be in
63  // scope of subsequent reachable statements.
64  assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
65  return;
66  }
67 
68  // Otherwise, make a new block to hold the code.
70  }
71 
72  // Generate a stoppoint if we are emitting debug info.
73  EmitStopPoint(S);
74 
75  // Ignore all OpenMP directives except for simd if OpenMP with Simd is
76  // enabled.
77  if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
78  if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
80  return;
81  }
82  }
83 
84  switch (S->getStmtClass()) {
85  case Stmt::NoStmtClass:
86  case Stmt::CXXCatchStmtClass:
87  case Stmt::SEHExceptStmtClass:
88  case Stmt::SEHFinallyStmtClass:
89  case Stmt::MSDependentExistsStmtClass:
90  llvm_unreachable("invalid statement class to emit generically");
91  case Stmt::NullStmtClass:
92  case Stmt::CompoundStmtClass:
93  case Stmt::DeclStmtClass:
94  case Stmt::LabelStmtClass:
95  case Stmt::AttributedStmtClass:
96  case Stmt::GotoStmtClass:
97  case Stmt::BreakStmtClass:
98  case Stmt::ContinueStmtClass:
99  case Stmt::DefaultStmtClass:
100  case Stmt::CaseStmtClass:
101  case Stmt::SEHLeaveStmtClass:
102  llvm_unreachable("should have emitted these statements as simple");
103 
104 #define STMT(Type, Base)
105 #define ABSTRACT_STMT(Op)
106 #define EXPR(Type, Base) \
107  case Stmt::Type##Class:
108 #include "clang/AST/StmtNodes.inc"
109  {
110  // Remember the block we came in on.
111  llvm::BasicBlock *incoming = Builder.GetInsertBlock();
112  assert(incoming && "expression emission must have an insertion point");
113 
114  EmitIgnoredExpr(cast<Expr>(S));
115 
116  llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
117  assert(outgoing && "expression emission cleared block!");
118 
119  // The expression emitters assume (reasonably!) that the insertion
120  // point is always set. To maintain that, the call-emission code
121  // for noreturn functions has to enter a new block with no
122  // predecessors. We want to kill that block and mark the current
123  // insertion point unreachable in the common case of a call like
124  // "exit();". Since expression emission doesn't otherwise create
125  // blocks with no predecessors, we can just test for that.
126  // However, we must be careful not to do this to our incoming
127  // block, because *statement* emission does sometimes create
128  // reachable blocks which will have no predecessors until later in
129  // the function. This occurs with, e.g., labels that are not
130  // reachable by fallthrough.
131  if (incoming != outgoing && outgoing->use_empty()) {
132  outgoing->eraseFromParent();
133  Builder.ClearInsertionPoint();
134  }
135  break;
136  }
137 
138  case Stmt::IndirectGotoStmtClass:
139  EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
140 
141  case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
142  case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
143  case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
144  case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
145 
146  case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
147 
148  case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
149  case Stmt::GCCAsmStmtClass: // Intentional fall-through.
150  case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
151  case Stmt::CoroutineBodyStmtClass:
152  EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
153  break;
154  case Stmt::CoreturnStmtClass:
155  EmitCoreturnStmt(cast<CoreturnStmt>(*S));
156  break;
157  case Stmt::CapturedStmtClass: {
158  const CapturedStmt *CS = cast<CapturedStmt>(S);
160  }
161  break;
162  case Stmt::ObjCAtTryStmtClass:
163  EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
164  break;
165  case Stmt::ObjCAtCatchStmtClass:
166  llvm_unreachable(
167  "@catch statements should be handled by EmitObjCAtTryStmt");
168  case Stmt::ObjCAtFinallyStmtClass:
169  llvm_unreachable(
170  "@finally statements should be handled by EmitObjCAtTryStmt");
171  case Stmt::ObjCAtThrowStmtClass:
172  EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
173  break;
174  case Stmt::ObjCAtSynchronizedStmtClass:
175  EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
176  break;
177  case Stmt::ObjCForCollectionStmtClass:
178  EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
179  break;
180  case Stmt::ObjCAutoreleasePoolStmtClass:
181  EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
182  break;
183 
184  case Stmt::CXXTryStmtClass:
185  EmitCXXTryStmt(cast<CXXTryStmt>(*S));
186  break;
187  case Stmt::CXXForRangeStmtClass:
188  EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
189  break;
190  case Stmt::SEHTryStmtClass:
191  EmitSEHTryStmt(cast<SEHTryStmt>(*S));
192  break;
193  case Stmt::OMPParallelDirectiveClass:
194  EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
195  break;
196  case Stmt::OMPSimdDirectiveClass:
197  EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
198  break;
199  case Stmt::OMPForDirectiveClass:
200  EmitOMPForDirective(cast<OMPForDirective>(*S));
201  break;
202  case Stmt::OMPForSimdDirectiveClass:
203  EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
204  break;
205  case Stmt::OMPSectionsDirectiveClass:
206  EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
207  break;
208  case Stmt::OMPSectionDirectiveClass:
209  EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
210  break;
211  case Stmt::OMPSingleDirectiveClass:
212  EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
213  break;
214  case Stmt::OMPMasterDirectiveClass:
215  EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
216  break;
217  case Stmt::OMPCriticalDirectiveClass:
218  EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
219  break;
220  case Stmt::OMPParallelForDirectiveClass:
221  EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
222  break;
223  case Stmt::OMPParallelForSimdDirectiveClass:
224  EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
225  break;
226  case Stmt::OMPParallelSectionsDirectiveClass:
227  EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
228  break;
229  case Stmt::OMPTaskDirectiveClass:
230  EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
231  break;
232  case Stmt::OMPTaskyieldDirectiveClass:
233  EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
234  break;
235  case Stmt::OMPBarrierDirectiveClass:
236  EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
237  break;
238  case Stmt::OMPTaskwaitDirectiveClass:
239  EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
240  break;
241  case Stmt::OMPTaskgroupDirectiveClass:
242  EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
243  break;
244  case Stmt::OMPFlushDirectiveClass:
245  EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
246  break;
247  case Stmt::OMPOrderedDirectiveClass:
248  EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
249  break;
250  case Stmt::OMPAtomicDirectiveClass:
251  EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
252  break;
253  case Stmt::OMPTargetDirectiveClass:
254  EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
255  break;
256  case Stmt::OMPTeamsDirectiveClass:
257  EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
258  break;
259  case Stmt::OMPCancellationPointDirectiveClass:
260  EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
261  break;
262  case Stmt::OMPCancelDirectiveClass:
263  EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
264  break;
265  case Stmt::OMPTargetDataDirectiveClass:
266  EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
267  break;
268  case Stmt::OMPTargetEnterDataDirectiveClass:
269  EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
270  break;
271  case Stmt::OMPTargetExitDataDirectiveClass:
272  EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
273  break;
274  case Stmt::OMPTargetParallelDirectiveClass:
275  EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
276  break;
277  case Stmt::OMPTargetParallelForDirectiveClass:
278  EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
279  break;
280  case Stmt::OMPTaskLoopDirectiveClass:
281  EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
282  break;
283  case Stmt::OMPTaskLoopSimdDirectiveClass:
284  EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
285  break;
286  case Stmt::OMPDistributeDirectiveClass:
287  EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
288  break;
289  case Stmt::OMPTargetUpdateDirectiveClass:
290  EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
291  break;
292  case Stmt::OMPDistributeParallelForDirectiveClass:
294  cast<OMPDistributeParallelForDirective>(*S));
295  break;
296  case Stmt::OMPDistributeParallelForSimdDirectiveClass:
298  cast<OMPDistributeParallelForSimdDirective>(*S));
299  break;
300  case Stmt::OMPDistributeSimdDirectiveClass:
301  EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
302  break;
303  case Stmt::OMPTargetParallelForSimdDirectiveClass:
305  cast<OMPTargetParallelForSimdDirective>(*S));
306  break;
307  case Stmt::OMPTargetSimdDirectiveClass:
308  EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
309  break;
310  case Stmt::OMPTeamsDistributeDirectiveClass:
311  EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
312  break;
313  case Stmt::OMPTeamsDistributeSimdDirectiveClass:
315  cast<OMPTeamsDistributeSimdDirective>(*S));
316  break;
317  case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
319  cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
320  break;
321  case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
323  cast<OMPTeamsDistributeParallelForDirective>(*S));
324  break;
325  case Stmt::OMPTargetTeamsDirectiveClass:
326  EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
327  break;
328  case Stmt::OMPTargetTeamsDistributeDirectiveClass:
330  cast<OMPTargetTeamsDistributeDirective>(*S));
331  break;
332  case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
334  cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
335  break;
336  case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
338  cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
339  break;
340  case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
342  cast<OMPTargetTeamsDistributeSimdDirective>(*S));
343  break;
344  }
345 }
346 
348  switch (S->getStmtClass()) {
349  default: return false;
350  case Stmt::NullStmtClass: break;
351  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
352  case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
353  case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
354  case Stmt::AttributedStmtClass:
355  EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
356  case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
357  case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
358  case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
359  case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
360  case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
361  case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
362  }
363 
364  return true;
365 }
366 
367 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
368 /// this captures the expression result of the last sub-statement and returns it
369 /// (for use by the statement expression extension).
371  AggValueSlot AggSlot) {
372  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
373  "LLVM IR generation of compound statement ('{}')");
374 
375  // Keep track of the current cleanup stack depth, including debug scopes.
376  LexicalScope Scope(*this, S.getSourceRange());
377 
378  return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
379 }
380 
381 Address
383  bool GetLast,
384  AggValueSlot AggSlot) {
385 
387  E = S.body_end()-GetLast; I != E; ++I)
388  EmitStmt(*I);
389 
390  Address RetAlloca = Address::invalid();
391  if (GetLast) {
392  // We have to special case labels here. They are statements, but when put
393  // at the end of a statement expression, they yield the value of their
394  // subexpression. Handle this by walking through all labels we encounter,
395  // emitting them before we evaluate the subexpr.
396  const Stmt *LastStmt = S.body_back();
397  while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
398  EmitLabel(LS->getDecl());
399  LastStmt = LS->getSubStmt();
400  }
401 
403 
404  QualType ExprTy = cast<Expr>(LastStmt)->getType();
405  if (hasAggregateEvaluationKind(ExprTy)) {
406  EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
407  } else {
408  // We can't return an RValue here because there might be cleanups at
409  // the end of the StmtExpr. Because of that, we have to emit the result
410  // here into a temporary alloca.
411  RetAlloca = CreateMemTemp(ExprTy);
412  EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
413  /*IsInit*/false);
414  }
415 
416  }
417 
418  return RetAlloca;
419 }
420 
421 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
422  llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
423 
424  // If there is a cleanup stack, then we it isn't worth trying to
425  // simplify this block (we would need to remove it from the scope map
426  // and cleanup entry).
427  if (!EHStack.empty())
428  return;
429 
430  // Can only simplify direct branches.
431  if (!BI || !BI->isUnconditional())
432  return;
433 
434  // Can only simplify empty blocks.
435  if (BI->getIterator() != BB->begin())
436  return;
437 
438  BB->replaceAllUsesWith(BI->getSuccessor(0));
439  BI->eraseFromParent();
440  BB->eraseFromParent();
441 }
442 
443 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
444  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
445 
446  // Fall out of the current block (if necessary).
447  EmitBranch(BB);
448 
449  if (IsFinished && BB->use_empty()) {
450  delete BB;
451  return;
452  }
453 
454  // Place the block after the current block, if possible, or else at
455  // the end of the function.
456  if (CurBB && CurBB->getParent())
457  CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
458  else
459  CurFn->getBasicBlockList().push_back(BB);
460  Builder.SetInsertPoint(BB);
461 }
462 
463 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
464  // Emit a branch from the current block to the target one if this
465  // was a real block. If this was just a fall-through block after a
466  // terminator, don't emit it.
467  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
468 
469  if (!CurBB || CurBB->getTerminator()) {
470  // If there is no insert point or the previous block is already
471  // terminated, don't touch it.
472  } else {
473  // Otherwise, create a fall-through branch.
474  Builder.CreateBr(Target);
475  }
476 
477  Builder.ClearInsertionPoint();
478 }
479 
480 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
481  bool inserted = false;
482  for (llvm::User *u : block->users()) {
483  if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
484  CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
485  block);
486  inserted = true;
487  break;
488  }
489  }
490 
491  if (!inserted)
492  CurFn->getBasicBlockList().push_back(block);
493 
494  Builder.SetInsertPoint(block);
495 }
496 
499  JumpDest &Dest = LabelMap[D];
500  if (Dest.isValid()) return Dest;
501 
502  // Create, but don't insert, the new block.
503  Dest = JumpDest(createBasicBlock(D->getName()),
506  return Dest;
507 }
508 
510  // Add this label to the current lexical scope if we're within any
511  // normal cleanups. Jumps "in" to this label --- when permitted by
512  // the language --- may need to be routed around such cleanups.
513  if (EHStack.hasNormalCleanups() && CurLexicalScope)
514  CurLexicalScope->addLabel(D);
515 
516  JumpDest &Dest = LabelMap[D];
517 
518  // If we didn't need a forward reference to this label, just go
519  // ahead and create a destination at the current scope.
520  if (!Dest.isValid()) {
521  Dest = getJumpDestInCurrentScope(D->getName());
522 
523  // Otherwise, we need to give this label a target depth and remove
524  // it from the branch-fixups list.
525  } else {
526  assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
529  }
530 
531  EmitBlock(Dest.getBlock());
533 }
534 
535 /// Change the cleanup scope of the labels in this lexical scope to
536 /// match the scope of the enclosing context.
538  assert(!Labels.empty());
539  EHScopeStack::stable_iterator innermostScope
540  = CGF.EHStack.getInnermostNormalCleanup();
541 
542  // Change the scope depth of all the labels.
544  i = Labels.begin(), e = Labels.end(); i != e; ++i) {
545  assert(CGF.LabelMap.count(*i));
546  JumpDest &dest = CGF.LabelMap.find(*i)->second;
547  assert(dest.getScopeDepth().isValid());
548  assert(innermostScope.encloses(dest.getScopeDepth()));
549  dest.setScopeDepth(innermostScope);
550  }
551 
552  // Reparent the labels if the new scope also has cleanups.
553  if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
554  ParentScope->Labels.append(Labels.begin(), Labels.end());
555  }
556 }
557 
558 
560  EmitLabel(S.getDecl());
561  EmitStmt(S.getSubStmt());
562 }
563 
565  EmitStmt(S.getSubStmt(), S.getAttrs());
566 }
567 
569  // If this code is reachable then emit a stop point (if generating
570  // debug info). We have to do this ourselves because we are on the
571  // "simple" statement path.
572  if (HaveInsertPoint())
573  EmitStopPoint(&S);
574 
576 }
577 
578 
580  if (const LabelDecl *Target = S.getConstantTarget()) {
582  return;
583  }
584 
585  // Ensure that we have an i8* for our PHI node.
587  Int8PtrTy, "addr");
588  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
589 
590  // Get the basic block for the indirect goto.
591  llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
592 
593  // The first instruction in the block has to be the PHI for the switch dest,
594  // add an entry for this branch.
595  cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
596 
597  EmitBranch(IndGotoBB);
598 }
599 
601  // C99 6.8.4.1: The first substatement is executed if the expression compares
602  // unequal to 0. The condition must be a scalar type.
603  LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
604 
605  if (S.getInit())
606  EmitStmt(S.getInit());
607 
608  if (S.getConditionVariable())
610 
611  // If the condition constant folds and can be elided, try to avoid emitting
612  // the condition and the dead arm of the if/else.
613  bool CondConstant;
614  if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
615  S.isConstexpr())) {
616  // Figure out which block (then or else) is executed.
617  const Stmt *Executed = S.getThen();
618  const Stmt *Skipped = S.getElse();
619  if (!CondConstant) // Condition false?
620  std::swap(Executed, Skipped);
621 
622  // If the skipped block has no labels in it, just emit the executed block.
623  // This avoids emitting dead code and simplifies the CFG substantially.
624  if (S.isConstexpr() || !ContainsLabel(Skipped)) {
625  if (CondConstant)
627  if (Executed) {
628  RunCleanupsScope ExecutedScope(*this);
629  EmitStmt(Executed);
630  }
631  return;
632  }
633  }
634 
635  // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
636  // the conditional branch.
637  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
638  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
639  llvm::BasicBlock *ElseBlock = ContBlock;
640  if (S.getElse())
641  ElseBlock = createBasicBlock("if.else");
642 
643  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
644  getProfileCount(S.getThen()));
645 
646  // Emit the 'then' code.
647  EmitBlock(ThenBlock);
649  {
650  RunCleanupsScope ThenScope(*this);
651  EmitStmt(S.getThen());
652  }
653  EmitBranch(ContBlock);
654 
655  // Emit the 'else' code if present.
656  if (const Stmt *Else = S.getElse()) {
657  {
658  // There is no need to emit line number for an unconditional branch.
659  auto NL = ApplyDebugLocation::CreateEmpty(*this);
660  EmitBlock(ElseBlock);
661  }
662  {
663  RunCleanupsScope ElseScope(*this);
664  EmitStmt(Else);
665  }
666  {
667  // There is no need to emit line number for an unconditional branch.
668  auto NL = ApplyDebugLocation::CreateEmpty(*this);
669  EmitBranch(ContBlock);
670  }
671  }
672 
673  // Emit the continuation block for code after the if.
674  EmitBlock(ContBlock, true);
675 }
676 
678  ArrayRef<const Attr *> WhileAttrs) {
679  // Emit the header for the loop, which will also become
680  // the continue target.
681  JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
682  EmitBlock(LoopHeader.getBlock());
683 
684  const SourceRange &R = S.getSourceRange();
685  LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
686  SourceLocToDebugLoc(R.getBegin()),
687  SourceLocToDebugLoc(R.getEnd()));
688 
689  // Create an exit block for when the condition fails, which will
690  // also become the break target.
692 
693  // Store the blocks to use for break and continue.
694  BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
695 
696  // C++ [stmt.while]p2:
697  // When the condition of a while statement is a declaration, the
698  // scope of the variable that is declared extends from its point
699  // of declaration (3.3.2) to the end of the while statement.
700  // [...]
701  // The object created in a condition is destroyed and created
702  // with each iteration of the loop.
703  RunCleanupsScope ConditionScope(*this);
704 
705  if (S.getConditionVariable())
707 
708  // Evaluate the conditional in the while header. C99 6.8.5.1: The
709  // evaluation of the controlling expression takes place before each
710  // execution of the loop body.
711  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
712 
713  // while(1) is common, avoid extra exit blocks. Be sure
714  // to correctly handle break/continue though.
715  bool EmitBoolCondBranch = true;
716  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
717  if (C->isOne())
718  EmitBoolCondBranch = false;
719 
720  // As long as the condition is true, go to the loop body.
721  llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
722  if (EmitBoolCondBranch) {
723  llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
724  if (ConditionScope.requiresCleanups())
725  ExitBlock = createBasicBlock("while.exit");
726  Builder.CreateCondBr(
727  BoolCondVal, LoopBody, ExitBlock,
728  createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
729 
730  if (ExitBlock != LoopExit.getBlock()) {
731  EmitBlock(ExitBlock);
732  EmitBranchThroughCleanup(LoopExit);
733  }
734  }
735 
736  // Emit the loop body. We have to emit this in a cleanup scope
737  // because it might be a singleton DeclStmt.
738  {
739  RunCleanupsScope BodyScope(*this);
740  EmitBlock(LoopBody);
742  EmitStmt(S.getBody());
743  }
744 
745  BreakContinueStack.pop_back();
746 
747  // Immediately force cleanup.
748  ConditionScope.ForceCleanup();
749 
750  EmitStopPoint(&S);
751  // Branch to the loop header again.
752  EmitBranch(LoopHeader.getBlock());
753 
754  LoopStack.pop();
755 
756  // Emit the exit block.
757  EmitBlock(LoopExit.getBlock(), true);
758 
759  // The LoopHeader typically is just a branch if we skipped emitting
760  // a branch, try to erase it.
761  if (!EmitBoolCondBranch)
762  SimplifyForwardingBlocks(LoopHeader.getBlock());
763 }
764 
766  ArrayRef<const Attr *> DoAttrs) {
768  JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
769 
770  uint64_t ParentCount = getCurrentProfileCount();
771 
772  // Store the blocks to use for break and continue.
773  BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
774 
775  // Emit the body of the loop.
776  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
777 
778  EmitBlockWithFallThrough(LoopBody, &S);
779  {
780  RunCleanupsScope BodyScope(*this);
781  EmitStmt(S.getBody());
782  }
783 
784  EmitBlock(LoopCond.getBlock());
785 
786  const SourceRange &R = S.getSourceRange();
787  LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
788  SourceLocToDebugLoc(R.getBegin()),
789  SourceLocToDebugLoc(R.getEnd()));
790 
791  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
792  // after each execution of the loop body."
793 
794  // Evaluate the conditional in the while header.
795  // C99 6.8.5p2/p4: The first substatement is executed if the expression
796  // compares unequal to 0. The condition must be a scalar type.
797  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
798 
799  BreakContinueStack.pop_back();
800 
801  // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
802  // to correctly handle break/continue though.
803  bool EmitBoolCondBranch = true;
804  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
805  if (C->isZero())
806  EmitBoolCondBranch = false;
807 
808  // As long as the condition is true, iterate the loop.
809  if (EmitBoolCondBranch) {
810  uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
811  Builder.CreateCondBr(
812  BoolCondVal, LoopBody, LoopExit.getBlock(),
813  createProfileWeightsForLoop(S.getCond(), BackedgeCount));
814  }
815 
816  LoopStack.pop();
817 
818  // Emit the exit block.
819  EmitBlock(LoopExit.getBlock());
820 
821  // The DoCond block typically is just a branch if we skipped
822  // emitting a branch, try to erase it.
823  if (!EmitBoolCondBranch)
825 }
826 
828  ArrayRef<const Attr *> ForAttrs) {
830 
831  LexicalScope ForScope(*this, S.getSourceRange());
832 
833  // Evaluate the first part before the loop.
834  if (S.getInit())
835  EmitStmt(S.getInit());
836 
837  // Start the loop with a block that tests the condition.
838  // If there's an increment, the continue scope will be overwritten
839  // later.
840  JumpDest Continue = getJumpDestInCurrentScope("for.cond");
841  llvm::BasicBlock *CondBlock = Continue.getBlock();
842  EmitBlock(CondBlock);
843 
844  const SourceRange &R = S.getSourceRange();
845  LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
848 
849  // If the for loop doesn't have an increment we can just use the
850  // condition as the continue block. Otherwise we'll need to create
851  // a block for it (in the current scope, i.e. in the scope of the
852  // condition), and that we will become our continue block.
853  if (S.getInc())
854  Continue = getJumpDestInCurrentScope("for.inc");
855 
856  // Store the blocks to use for break and continue.
857  BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
858 
859  // Create a cleanup scope for the condition variable cleanups.
860  LexicalScope ConditionScope(*this, S.getSourceRange());
861 
862  if (S.getCond()) {
863  // If the for statement has a condition scope, emit the local variable
864  // declaration.
865  if (S.getConditionVariable()) {
867  }
868 
869  llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
870  // If there are any cleanups between here and the loop-exit scope,
871  // create a block to stage a loop exit along.
872  if (ForScope.requiresCleanups())
873  ExitBlock = createBasicBlock("for.cond.cleanup");
874 
875  // As long as the condition is true, iterate the loop.
876  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
877 
878  // C99 6.8.5p2/p4: The first substatement is executed if the expression
879  // compares unequal to 0. The condition must be a scalar type.
880  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
881  Builder.CreateCondBr(
882  BoolCondVal, ForBody, ExitBlock,
883  createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
884 
885  if (ExitBlock != LoopExit.getBlock()) {
886  EmitBlock(ExitBlock);
887  EmitBranchThroughCleanup(LoopExit);
888  }
889 
890  EmitBlock(ForBody);
891  } else {
892  // Treat it as a non-zero constant. Don't even create a new block for the
893  // body, just fall into it.
894  }
896 
897  {
898  // Create a separate cleanup scope for the body, in case it is not
899  // a compound statement.
900  RunCleanupsScope BodyScope(*this);
901  EmitStmt(S.getBody());
902  }
903 
904  // If there is an increment, emit it next.
905  if (S.getInc()) {
906  EmitBlock(Continue.getBlock());
907  EmitStmt(S.getInc());
908  }
909 
910  BreakContinueStack.pop_back();
911 
912  ConditionScope.ForceCleanup();
913 
914  EmitStopPoint(&S);
915  EmitBranch(CondBlock);
916 
917  ForScope.ForceCleanup();
918 
919  LoopStack.pop();
920 
921  // Emit the fall-through block.
922  EmitBlock(LoopExit.getBlock(), true);
923 }
924 
925 void
927  ArrayRef<const Attr *> ForAttrs) {
929 
930  LexicalScope ForScope(*this, S.getSourceRange());
931 
932  // Evaluate the first pieces before the loop.
933  if (S.getInit())
934  EmitStmt(S.getInit());
935  EmitStmt(S.getRangeStmt());
936  EmitStmt(S.getBeginStmt());
937  EmitStmt(S.getEndStmt());
938 
939  // Start the loop with a block that tests the condition.
940  // If there's an increment, the continue scope will be overwritten
941  // later.
942  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
943  EmitBlock(CondBlock);
944 
945  const SourceRange &R = S.getSourceRange();
946  LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
949 
950  // If there are any cleanups between here and the loop-exit scope,
951  // create a block to stage a loop exit along.
952  llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
953  if (ForScope.requiresCleanups())
954  ExitBlock = createBasicBlock("for.cond.cleanup");
955 
956  // The loop body, consisting of the specified body and the loop variable.
957  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
958 
959  // The body is executed if the expression, contextually converted
960  // to bool, is true.
961  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
962  Builder.CreateCondBr(
963  BoolCondVal, ForBody, ExitBlock,
964  createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
965 
966  if (ExitBlock != LoopExit.getBlock()) {
967  EmitBlock(ExitBlock);
968  EmitBranchThroughCleanup(LoopExit);
969  }
970 
971  EmitBlock(ForBody);
973 
974  // Create a block for the increment. In case of a 'continue', we jump there.
975  JumpDest Continue = getJumpDestInCurrentScope("for.inc");
976 
977  // Store the blocks to use for break and continue.
978  BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
979 
980  {
981  // Create a separate cleanup scope for the loop variable and body.
982  LexicalScope BodyScope(*this, S.getSourceRange());
984  EmitStmt(S.getBody());
985  }
986 
987  EmitStopPoint(&S);
988  // If there is an increment, emit it next.
989  EmitBlock(Continue.getBlock());
990  EmitStmt(S.getInc());
991 
992  BreakContinueStack.pop_back();
993 
994  EmitBranch(CondBlock);
995 
996  ForScope.ForceCleanup();
997 
998  LoopStack.pop();
999 
1000  // Emit the fall-through block.
1001  EmitBlock(LoopExit.getBlock(), true);
1002 }
1003 
1004 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1005  if (RV.isScalar()) {
1007  } else if (RV.isAggregate()) {
1008  LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1009  LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
1010  EmitAggregateCopy(Dest, Src, Ty, overlapForReturnValue());
1011  } else {
1013  /*init*/ true);
1014  }
1016 }
1017 
1018 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1019 /// if the function returns void, or may be missing one if the function returns
1020 /// non-void. Fun stuff :).
1022  if (requiresReturnValueCheck()) {
1023  llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1024  auto *SLocPtr =
1025  new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1026  llvm::GlobalVariable::PrivateLinkage, SLoc);
1027  SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1029  assert(ReturnLocation.isValid() && "No valid return location");
1031  ReturnLocation);
1032  }
1033 
1034  // Returning from an outlined SEH helper is UB, and we already warn on it.
1035  if (IsOutlinedSEHHelper) {
1036  Builder.CreateUnreachable();
1037  Builder.ClearInsertionPoint();
1038  }
1039 
1040  // Emit the result value, even if unused, to evaluate the side effects.
1041  const Expr *RV = S.getRetValue();
1042 
1043  // Treat block literals in a return expression as if they appeared
1044  // in their own scope. This permits a small, easily-implemented
1045  // exception to our over-conservative rules about not jumping to
1046  // statements following block literals with non-trivial cleanups.
1047  RunCleanupsScope cleanupScope(*this);
1048  if (const FullExpr *fe = dyn_cast_or_null<FullExpr>(RV)) {
1049  enterFullExpression(fe);
1050  RV = fe->getSubExpr();
1051  }
1052 
1053  // FIXME: Clean this up by using an LValue for ReturnTemp,
1054  // EmitStoreThroughLValue, and EmitAnyExpr.
1055  if (getLangOpts().ElideConstructors &&
1057  // Apply the named return value optimization for this return statement,
1058  // which means doing nothing: the appropriate result has already been
1059  // constructed into the NRVO variable.
1060 
1061  // If there is an NRVO flag for this variable, set it to 1 into indicate
1062  // that the cleanup code should not destroy the variable.
1063  if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1064  Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1065  } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1066  // Make sure not to return anything, but evaluate the expression
1067  // for side effects.
1068  if (RV)
1069  EmitAnyExpr(RV);
1070  } else if (!RV) {
1071  // Do nothing (return value is left uninitialized)
1072  } else if (FnRetTy->isReferenceType()) {
1073  // If this function returns a reference, take the address of the expression
1074  // rather than the value.
1075  RValue Result = EmitReferenceBindingToExpr(RV);
1077  } else {
1078  switch (getEvaluationKind(RV->getType())) {
1079  case TEK_Scalar:
1081  break;
1082  case TEK_Complex:
1084  /*isInit*/ true);
1085  break;
1086  case TEK_Aggregate:
1093  break;
1094  }
1095  }
1096 
1097  ++NumReturnExprs;
1098  if (!RV || RV->isEvaluatable(getContext()))
1099  ++NumSimpleReturnExprs;
1100 
1101  cleanupScope.ForceCleanup();
1103 }
1104 
1106  // As long as debug info is modeled with instructions, we have to ensure we
1107  // have a place to insert here and write the stop point here.
1108  if (HaveInsertPoint())
1109  EmitStopPoint(&S);
1110 
1111  for (const auto *I : S.decls())
1112  EmitDecl(*I);
1113 }
1114 
1116  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1117 
1118  // If this code is reachable then emit a stop point (if generating
1119  // debug info). We have to do this ourselves because we are on the
1120  // "simple" statement path.
1121  if (HaveInsertPoint())
1122  EmitStopPoint(&S);
1123 
1124  EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1125 }
1126 
1128  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1129 
1130  // If this code is reachable then emit a stop point (if generating
1131  // debug info). We have to do this ourselves because we are on the
1132  // "simple" statement path.
1133  if (HaveInsertPoint())
1134  EmitStopPoint(&S);
1135 
1136  EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1137 }
1138 
1139 /// EmitCaseStmtRange - If case statement range is not too big then
1140 /// add multiple cases to switch instruction, one for each value within
1141 /// the range. If range is too big then emit "if" condition check.
1143  assert(S.getRHS() && "Expected RHS value in CaseStmt");
1144 
1145  llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1146  llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1147 
1148  // Emit the code for this case. We do this first to make sure it is
1149  // properly chained from our predecessor before generating the
1150  // switch machinery to enter this block.
1151  llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1152  EmitBlockWithFallThrough(CaseDest, &S);
1153  EmitStmt(S.getSubStmt());
1154 
1155  // If range is empty, do nothing.
1156  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1157  return;
1158 
1159  llvm::APInt Range = RHS - LHS;
1160  // FIXME: parameters such as this should not be hardcoded.
1161  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1162  // Range is small enough to add multiple switch instruction cases.
1163  uint64_t Total = getProfileCount(&S);
1164  unsigned NCases = Range.getZExtValue() + 1;
1165  // We only have one region counter for the entire set of cases here, so we
1166  // need to divide the weights evenly between the generated cases, ensuring
1167  // that the total weight is preserved. E.g., a weight of 5 over three cases
1168  // will be distributed as weights of 2, 2, and 1.
1169  uint64_t Weight = Total / NCases, Rem = Total % NCases;
1170  for (unsigned I = 0; I != NCases; ++I) {
1171  if (SwitchWeights)
1172  SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1173  if (Rem)
1174  Rem--;
1175  SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1176  ++LHS;
1177  }
1178  return;
1179  }
1180 
1181  // The range is too big. Emit "if" condition into a new block,
1182  // making sure to save and restore the current insertion point.
1183  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1184 
1185  // Push this test onto the chain of range checks (which terminates
1186  // in the default basic block). The switch's default will be changed
1187  // to the top of this chain after switch emission is complete.
1188  llvm::BasicBlock *FalseDest = CaseRangeBlock;
1189  CaseRangeBlock = createBasicBlock("sw.caserange");
1190 
1191  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1192  Builder.SetInsertPoint(CaseRangeBlock);
1193 
1194  // Emit range check.
1195  llvm::Value *Diff =
1196  Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1197  llvm::Value *Cond =
1198  Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1199 
1200  llvm::MDNode *Weights = nullptr;
1201  if (SwitchWeights) {
1202  uint64_t ThisCount = getProfileCount(&S);
1203  uint64_t DefaultCount = (*SwitchWeights)[0];
1204  Weights = createProfileWeights(ThisCount, DefaultCount);
1205 
1206  // Since we're chaining the switch default through each large case range, we
1207  // need to update the weight for the default, ie, the first case, to include
1208  // this case.
1209  (*SwitchWeights)[0] += ThisCount;
1210  }
1211  Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1212 
1213  // Restore the appropriate insertion point.
1214  if (RestoreBB)
1215  Builder.SetInsertPoint(RestoreBB);
1216  else
1217  Builder.ClearInsertionPoint();
1218 }
1219 
1221  // If there is no enclosing switch instance that we're aware of, then this
1222  // case statement and its block can be elided. This situation only happens
1223  // when we've constant-folded the switch, are emitting the constant case,
1224  // and part of the constant case includes another case statement. For
1225  // instance: switch (4) { case 4: do { case 5: } while (1); }
1226  if (!SwitchInsn) {
1227  EmitStmt(S.getSubStmt());
1228  return;
1229  }
1230 
1231  // Handle case ranges.
1232  if (S.getRHS()) {
1233  EmitCaseStmtRange(S);
1234  return;
1235  }
1236 
1237  llvm::ConstantInt *CaseVal =
1239 
1240  // If the body of the case is just a 'break', try to not emit an empty block.
1241  // If we're profiling or we're not optimizing, leave the block in for better
1242  // debug and coverage analysis.
1244  CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1245  isa<BreakStmt>(S.getSubStmt())) {
1246  JumpDest Block = BreakContinueStack.back().BreakBlock;
1247 
1248  // Only do this optimization if there are no cleanups that need emitting.
1249  if (isObviouslyBranchWithoutCleanups(Block)) {
1250  if (SwitchWeights)
1251  SwitchWeights->push_back(getProfileCount(&S));
1252  SwitchInsn->addCase(CaseVal, Block.getBlock());
1253 
1254  // If there was a fallthrough into this case, make sure to redirect it to
1255  // the end of the switch as well.
1256  if (Builder.GetInsertBlock()) {
1257  Builder.CreateBr(Block.getBlock());
1258  Builder.ClearInsertionPoint();
1259  }
1260  return;
1261  }
1262  }
1263 
1264  llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1265  EmitBlockWithFallThrough(CaseDest, &S);
1266  if (SwitchWeights)
1267  SwitchWeights->push_back(getProfileCount(&S));
1268  SwitchInsn->addCase(CaseVal, CaseDest);
1269 
1270  // Recursively emitting the statement is acceptable, but is not wonderful for
1271  // code where we have many case statements nested together, i.e.:
1272  // case 1:
1273  // case 2:
1274  // case 3: etc.
1275  // Handling this recursively will create a new block for each case statement
1276  // that falls through to the next case which is IR intensive. It also causes
1277  // deep recursion which can run into stack depth limitations. Handle
1278  // sequential non-range case statements specially.
1279  const CaseStmt *CurCase = &S;
1280  const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1281 
1282  // Otherwise, iteratively add consecutive cases to this switch stmt.
1283  while (NextCase && NextCase->getRHS() == nullptr) {
1284  CurCase = NextCase;
1285  llvm::ConstantInt *CaseVal =
1286  Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1287 
1288  if (SwitchWeights)
1289  SwitchWeights->push_back(getProfileCount(NextCase));
1291  CaseDest = createBasicBlock("sw.bb");
1292  EmitBlockWithFallThrough(CaseDest, &S);
1293  }
1294 
1295  SwitchInsn->addCase(CaseVal, CaseDest);
1296  NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1297  }
1298 
1299  // Normal default recursion for non-cases.
1300  EmitStmt(CurCase->getSubStmt());
1301 }
1302 
1304  // If there is no enclosing switch instance that we're aware of, then this
1305  // default statement can be elided. This situation only happens when we've
1306  // constant-folded the switch.
1307  if (!SwitchInsn) {
1308  EmitStmt(S.getSubStmt());
1309  return;
1310  }
1311 
1312  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1313  assert(DefaultBlock->empty() &&
1314  "EmitDefaultStmt: Default block already defined?");
1315 
1316  EmitBlockWithFallThrough(DefaultBlock, &S);
1317 
1318  EmitStmt(S.getSubStmt());
1319 }
1320 
1321 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1322 /// constant value that is being switched on, see if we can dead code eliminate
1323 /// the body of the switch to a simple series of statements to emit. Basically,
1324 /// on a switch (5) we want to find these statements:
1325 /// case 5:
1326 /// printf(...); <--
1327 /// ++i; <--
1328 /// break;
1329 ///
1330 /// and add them to the ResultStmts vector. If it is unsafe to do this
1331 /// transformation (for example, one of the elided statements contains a label
1332 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1333 /// should include statements after it (e.g. the printf() line is a substmt of
1334 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1335 /// statement, then return CSFC_Success.
1336 ///
1337 /// If Case is non-null, then we are looking for the specified case, checking
1338 /// that nothing we jump over contains labels. If Case is null, then we found
1339 /// the case and are looking for the break.
1340 ///
1341 /// If the recursive walk actually finds our Case, then we set FoundCase to
1342 /// true.
1343 ///
1346  const SwitchCase *Case,
1347  bool &FoundCase,
1348  SmallVectorImpl<const Stmt*> &ResultStmts) {
1349  // If this is a null statement, just succeed.
1350  if (!S)
1351  return Case ? CSFC_Success : CSFC_FallThrough;
1352 
1353  // If this is the switchcase (case 4: or default) that we're looking for, then
1354  // we're in business. Just add the substatement.
1355  if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1356  if (S == Case) {
1357  FoundCase = true;
1358  return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1359  ResultStmts);
1360  }
1361 
1362  // Otherwise, this is some other case or default statement, just ignore it.
1363  return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1364  ResultStmts);
1365  }
1366 
1367  // If we are in the live part of the code and we found our break statement,
1368  // return a success!
1369  if (!Case && isa<BreakStmt>(S))
1370  return CSFC_Success;
1371 
1372  // If this is a switch statement, then it might contain the SwitchCase, the
1373  // break, or neither.
1374  if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1375  // Handle this as two cases: we might be looking for the SwitchCase (if so
1376  // the skipped statements must be skippable) or we might already have it.
1377  CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1378  bool StartedInLiveCode = FoundCase;
1379  unsigned StartSize = ResultStmts.size();
1380 
1381  // If we've not found the case yet, scan through looking for it.
1382  if (Case) {
1383  // Keep track of whether we see a skipped declaration. The code could be
1384  // using the declaration even if it is skipped, so we can't optimize out
1385  // the decl if the kept statements might refer to it.
1386  bool HadSkippedDecl = false;
1387 
1388  // If we're looking for the case, just see if we can skip each of the
1389  // substatements.
1390  for (; Case && I != E; ++I) {
1391  HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1392 
1393  switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1394  case CSFC_Failure: return CSFC_Failure;
1395  case CSFC_Success:
1396  // A successful result means that either 1) that the statement doesn't
1397  // have the case and is skippable, or 2) does contain the case value
1398  // and also contains the break to exit the switch. In the later case,
1399  // we just verify the rest of the statements are elidable.
1400  if (FoundCase) {
1401  // If we found the case and skipped declarations, we can't do the
1402  // optimization.
1403  if (HadSkippedDecl)
1404  return CSFC_Failure;
1405 
1406  for (++I; I != E; ++I)
1407  if (CodeGenFunction::ContainsLabel(*I, true))
1408  return CSFC_Failure;
1409  return CSFC_Success;
1410  }
1411  break;
1412  case CSFC_FallThrough:
1413  // If we have a fallthrough condition, then we must have found the
1414  // case started to include statements. Consider the rest of the
1415  // statements in the compound statement as candidates for inclusion.
1416  assert(FoundCase && "Didn't find case but returned fallthrough?");
1417  // We recursively found Case, so we're not looking for it anymore.
1418  Case = nullptr;
1419 
1420  // If we found the case and skipped declarations, we can't do the
1421  // optimization.
1422  if (HadSkippedDecl)
1423  return CSFC_Failure;
1424  break;
1425  }
1426  }
1427 
1428  if (!FoundCase)
1429  return CSFC_Success;
1430 
1431  assert(!HadSkippedDecl && "fallthrough after skipping decl");
1432  }
1433 
1434  // If we have statements in our range, then we know that the statements are
1435  // live and need to be added to the set of statements we're tracking.
1436  bool AnyDecls = false;
1437  for (; I != E; ++I) {
1438  AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1439 
1440  switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1441  case CSFC_Failure: return CSFC_Failure;
1442  case CSFC_FallThrough:
1443  // A fallthrough result means that the statement was simple and just
1444  // included in ResultStmt, keep adding them afterwards.
1445  break;
1446  case CSFC_Success:
1447  // A successful result means that we found the break statement and
1448  // stopped statement inclusion. We just ensure that any leftover stmts
1449  // are skippable and return success ourselves.
1450  for (++I; I != E; ++I)
1451  if (CodeGenFunction::ContainsLabel(*I, true))
1452  return CSFC_Failure;
1453  return CSFC_Success;
1454  }
1455  }
1456 
1457  // If we're about to fall out of a scope without hitting a 'break;', we
1458  // can't perform the optimization if there were any decls in that scope
1459  // (we'd lose their end-of-lifetime).
1460  if (AnyDecls) {
1461  // If the entire compound statement was live, there's one more thing we
1462  // can try before giving up: emit the whole thing as a single statement.
1463  // We can do that unless the statement contains a 'break;'.
1464  // FIXME: Such a break must be at the end of a construct within this one.
1465  // We could emit this by just ignoring the BreakStmts entirely.
1466  if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1467  ResultStmts.resize(StartSize);
1468  ResultStmts.push_back(S);
1469  } else {
1470  return CSFC_Failure;
1471  }
1472  }
1473 
1474  return CSFC_FallThrough;
1475  }
1476 
1477  // Okay, this is some other statement that we don't handle explicitly, like a
1478  // for statement or increment etc. If we are skipping over this statement,
1479  // just verify it doesn't have labels, which would make it invalid to elide.
1480  if (Case) {
1481  if (CodeGenFunction::ContainsLabel(S, true))
1482  return CSFC_Failure;
1483  return CSFC_Success;
1484  }
1485 
1486  // Otherwise, we want to include this statement. Everything is cool with that
1487  // so long as it doesn't contain a break out of the switch we're in.
1489 
1490  // Otherwise, everything is great. Include the statement and tell the caller
1491  // that we fall through and include the next statement as well.
1492  ResultStmts.push_back(S);
1493  return CSFC_FallThrough;
1494 }
1495 
1496 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1497 /// then invoke CollectStatementsForCase to find the list of statements to emit
1498 /// for a switch on constant. See the comment above CollectStatementsForCase
1499 /// for more details.
1501  const llvm::APSInt &ConstantCondValue,
1502  SmallVectorImpl<const Stmt*> &ResultStmts,
1503  ASTContext &C,
1504  const SwitchCase *&ResultCase) {
1505  // First step, find the switch case that is being branched to. We can do this
1506  // efficiently by scanning the SwitchCase list.
1507  const SwitchCase *Case = S.getSwitchCaseList();
1508  const DefaultStmt *DefaultCase = nullptr;
1509 
1510  for (; Case; Case = Case->getNextSwitchCase()) {
1511  // It's either a default or case. Just remember the default statement in
1512  // case we're not jumping to any numbered cases.
1513  if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1514  DefaultCase = DS;
1515  continue;
1516  }
1517 
1518  // Check to see if this case is the one we're looking for.
1519  const CaseStmt *CS = cast<CaseStmt>(Case);
1520  // Don't handle case ranges yet.
1521  if (CS->getRHS()) return false;
1522 
1523  // If we found our case, remember it as 'case'.
1524  if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1525  break;
1526  }
1527 
1528  // If we didn't find a matching case, we use a default if it exists, or we
1529  // elide the whole switch body!
1530  if (!Case) {
1531  // It is safe to elide the body of the switch if it doesn't contain labels
1532  // etc. If it is safe, return successfully with an empty ResultStmts list.
1533  if (!DefaultCase)
1534  return !CodeGenFunction::ContainsLabel(&S);
1535  Case = DefaultCase;
1536  }
1537 
1538  // Ok, we know which case is being jumped to, try to collect all the
1539  // statements that follow it. This can fail for a variety of reasons. Also,
1540  // check to see that the recursive walk actually found our case statement.
1541  // Insane cases like this can fail to find it in the recursive walk since we
1542  // don't handle every stmt kind:
1543  // switch (4) {
1544  // while (1) {
1545  // case 4: ...
1546  bool FoundCase = false;
1547  ResultCase = Case;
1548  return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1549  ResultStmts) != CSFC_Failure &&
1550  FoundCase;
1551 }
1552 
1554  // Handle nested switch statements.
1555  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1556  SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1557  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1558 
1559  // See if we can constant fold the condition of the switch and therefore only
1560  // emit the live case statement (if any) of the switch.
1561  llvm::APSInt ConstantCondValue;
1562  if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1563  SmallVector<const Stmt*, 4> CaseStmts;
1564  const SwitchCase *Case = nullptr;
1565  if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1566  getContext(), Case)) {
1567  if (Case)
1569  RunCleanupsScope ExecutedScope(*this);
1570 
1571  if (S.getInit())
1572  EmitStmt(S.getInit());
1573 
1574  // Emit the condition variable if needed inside the entire cleanup scope
1575  // used by this special case for constant folded switches.
1576  if (S.getConditionVariable())
1578 
1579  // At this point, we are no longer "within" a switch instance, so
1580  // we can temporarily enforce this to ensure that any embedded case
1581  // statements are not emitted.
1582  SwitchInsn = nullptr;
1583 
1584  // Okay, we can dead code eliminate everything except this case. Emit the
1585  // specified series of statements and we're good.
1586  for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1587  EmitStmt(CaseStmts[i]);
1589 
1590  // Now we want to restore the saved switch instance so that nested
1591  // switches continue to function properly
1592  SwitchInsn = SavedSwitchInsn;
1593 
1594  return;
1595  }
1596  }
1597 
1598  JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1599 
1600  RunCleanupsScope ConditionScope(*this);
1601 
1602  if (S.getInit())
1603  EmitStmt(S.getInit());
1604 
1605  if (S.getConditionVariable())
1607  llvm::Value *CondV = EmitScalarExpr(S.getCond());
1608 
1609  // Create basic block to hold stuff that comes after switch
1610  // statement. We also need to create a default block now so that
1611  // explicit case ranges tests can have a place to jump to on
1612  // failure.
1613  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1614  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1615  if (PGO.haveRegionCounts()) {
1616  // Walk the SwitchCase list to find how many there are.
1617  uint64_t DefaultCount = 0;
1618  unsigned NumCases = 0;
1619  for (const SwitchCase *Case = S.getSwitchCaseList();
1620  Case;
1621  Case = Case->getNextSwitchCase()) {
1622  if (isa<DefaultStmt>(Case))
1623  DefaultCount = getProfileCount(Case);
1624  NumCases += 1;
1625  }
1626  SwitchWeights = new SmallVector<uint64_t, 16>();
1627  SwitchWeights->reserve(NumCases);
1628  // The default needs to be first. We store the edge count, so we already
1629  // know the right weight.
1630  SwitchWeights->push_back(DefaultCount);
1631  }
1632  CaseRangeBlock = DefaultBlock;
1633 
1634  // Clear the insertion point to indicate we are in unreachable code.
1635  Builder.ClearInsertionPoint();
1636 
1637  // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1638  // then reuse last ContinueBlock.
1639  JumpDest OuterContinue;
1640  if (!BreakContinueStack.empty())
1641  OuterContinue = BreakContinueStack.back().ContinueBlock;
1642 
1643  BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1644 
1645  // Emit switch body.
1646  EmitStmt(S.getBody());
1647 
1648  BreakContinueStack.pop_back();
1649 
1650  // Update the default block in case explicit case range tests have
1651  // been chained on top.
1652  SwitchInsn->setDefaultDest(CaseRangeBlock);
1653 
1654  // If a default was never emitted:
1655  if (!DefaultBlock->getParent()) {
1656  // If we have cleanups, emit the default block so that there's a
1657  // place to jump through the cleanups from.
1658  if (ConditionScope.requiresCleanups()) {
1659  EmitBlock(DefaultBlock);
1660 
1661  // Otherwise, just forward the default block to the switch end.
1662  } else {
1663  DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1664  delete DefaultBlock;
1665  }
1666  }
1667 
1668  ConditionScope.ForceCleanup();
1669 
1670  // Emit continuation.
1671  EmitBlock(SwitchExit.getBlock(), true);
1673 
1674  // If the switch has a condition wrapped by __builtin_unpredictable,
1675  // create metadata that specifies that the switch is unpredictable.
1676  // Don't bother if not optimizing because that metadata would not be used.
1677  auto *Call = dyn_cast<CallExpr>(S.getCond());
1678  if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1679  auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1680  if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1681  llvm::MDBuilder MDHelper(getLLVMContext());
1682  SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1683  MDHelper.createUnpredictable());
1684  }
1685  }
1686 
1687  if (SwitchWeights) {
1688  assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1689  "switch weights do not match switch cases");
1690  // If there's only one jump destination there's no sense weighting it.
1691  if (SwitchWeights->size() > 1)
1692  SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1693  createProfileWeights(*SwitchWeights));
1694  delete SwitchWeights;
1695  }
1696  SwitchInsn = SavedSwitchInsn;
1697  SwitchWeights = SavedSwitchWeights;
1698  CaseRangeBlock = SavedCRBlock;
1699 }
1700 
1701 static std::string
1702 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1704  std::string Result;
1705 
1706  while (*Constraint) {
1707  switch (*Constraint) {
1708  default:
1709  Result += Target.convertConstraint(Constraint);
1710  break;
1711  // Ignore these
1712  case '*':
1713  case '?':
1714  case '!':
1715  case '=': // Will see this and the following in mult-alt constraints.
1716  case '+':
1717  break;
1718  case '#': // Ignore the rest of the constraint alternative.
1719  while (Constraint[1] && Constraint[1] != ',')
1720  Constraint++;
1721  break;
1722  case '&':
1723  case '%':
1724  Result += *Constraint;
1725  while (Constraint[1] && Constraint[1] == *Constraint)
1726  Constraint++;
1727  break;
1728  case ',':
1729  Result += "|";
1730  break;
1731  case 'g':
1732  Result += "imr";
1733  break;
1734  case '[': {
1735  assert(OutCons &&
1736  "Must pass output names to constraints with a symbolic name");
1737  unsigned Index;
1738  bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1739  assert(result && "Could not resolve symbolic name"); (void)result;
1740  Result += llvm::utostr(Index);
1741  break;
1742  }
1743  }
1744 
1745  Constraint++;
1746  }
1747 
1748  return Result;
1749 }
1750 
1751 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1752 /// as using a particular register add that as a constraint that will be used
1753 /// in this asm stmt.
1754 static std::string
1755 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1757  const AsmStmt &Stmt, const bool EarlyClobber) {
1758  const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1759  if (!AsmDeclRef)
1760  return Constraint;
1761  const ValueDecl &Value = *AsmDeclRef->getDecl();
1762  const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1763  if (!Variable)
1764  return Constraint;
1765  if (Variable->getStorageClass() != SC_Register)
1766  return Constraint;
1767  AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1768  if (!Attr)
1769  return Constraint;
1770  StringRef Register = Attr->getLabel();
1771  assert(Target.isValidGCCRegisterName(Register));
1772  // We're using validateOutputConstraint here because we only care if
1773  // this is a register constraint.
1774  TargetInfo::ConstraintInfo Info(Constraint, "");
1775  if (Target.validateOutputConstraint(Info) &&
1776  !Info.allowsRegister()) {
1777  CGM.ErrorUnsupported(&Stmt, "__asm__");
1778  return Constraint;
1779  }
1780  // Canonicalize the register here before returning it.
1781  Register = Target.getNormalizedGCCRegisterName(Register);
1782  return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1783 }
1784 
1785 llvm::Value*
1786 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1787  LValue InputValue, QualType InputType,
1788  std::string &ConstraintStr,
1789  SourceLocation Loc) {
1790  llvm::Value *Arg;
1791  if (Info.allowsRegister() || !Info.allowsMemory()) {
1793  Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1794  } else {
1795  llvm::Type *Ty = ConvertType(InputType);
1796  uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1797  if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1798  Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1799  Ty = llvm::PointerType::getUnqual(Ty);
1800 
1801  Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1802  Ty));
1803  } else {
1804  Arg = InputValue.getPointer();
1805  ConstraintStr += '*';
1806  }
1807  }
1808  } else {
1809  Arg = InputValue.getPointer();
1810  ConstraintStr += '*';
1811  }
1812 
1813  return Arg;
1814 }
1815 
1816 llvm::Value* CodeGenFunction::EmitAsmInput(
1817  const TargetInfo::ConstraintInfo &Info,
1818  const Expr *InputExpr,
1819  std::string &ConstraintStr) {
1820  // If this can't be a register or memory, i.e., has to be a constant
1821  // (immediate or symbolic), try to emit it as such.
1822  if (!Info.allowsRegister() && !Info.allowsMemory()) {
1823  Expr::EvalResult Result;
1824  if (InputExpr->EvaluateAsInt(Result, getContext()))
1825  return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
1826  assert(!Info.requiresImmediateConstant() &&
1827  "Required-immediate inlineasm arg isn't constant?");
1828  }
1829 
1830  if (Info.allowsRegister() || !Info.allowsMemory())
1832  return EmitScalarExpr(InputExpr);
1833  if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1834  return EmitScalarExpr(InputExpr);
1835  InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1836  LValue Dest = EmitLValue(InputExpr);
1837  return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1838  InputExpr->getExprLoc());
1839 }
1840 
1841 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1842 /// asm call instruction. The !srcloc MDNode contains a list of constant
1843 /// integers which are the source locations of the start of each line in the
1844 /// asm.
1845 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1846  CodeGenFunction &CGF) {
1848  // Add the location of the first line to the MDNode.
1849  Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1850  CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
1851  StringRef StrVal = Str->getString();
1852  if (!StrVal.empty()) {
1853  const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1854  const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1855  unsigned StartToken = 0;
1856  unsigned ByteOffset = 0;
1857 
1858  // Add the location of the start of each subsequent line of the asm to the
1859  // MDNode.
1860  for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1861  if (StrVal[i] != '\n') continue;
1862  SourceLocation LineLoc = Str->getLocationOfByte(
1863  i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1864  Locs.push_back(llvm::ConstantAsMetadata::get(
1865  llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1866  }
1867  }
1868 
1869  return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1870 }
1871 
1873  // Assemble the final asm string.
1874  std::string AsmString = S.generateAsmString(getContext());
1875 
1876  // Get all the output and input constraints together.
1877  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1878  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1879 
1880  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1881  StringRef Name;
1882  if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1883  Name = GAS->getOutputName(i);
1885  bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1886  assert(IsValid && "Failed to parse output constraint");
1887  OutputConstraintInfos.push_back(Info);
1888  }
1889 
1890  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1891  StringRef Name;
1892  if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1893  Name = GAS->getInputName(i);
1895  bool IsValid =
1896  getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1897  assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1898  InputConstraintInfos.push_back(Info);
1899  }
1900 
1901  std::string Constraints;
1902 
1903  std::vector<LValue> ResultRegDests;
1904  std::vector<QualType> ResultRegQualTys;
1905  std::vector<llvm::Type *> ResultRegTypes;
1906  std::vector<llvm::Type *> ResultTruncRegTypes;
1907  std::vector<llvm::Type *> ArgTypes;
1908  std::vector<llvm::Value*> Args;
1909 
1910  // Keep track of inout constraints.
1911  std::string InOutConstraints;
1912  std::vector<llvm::Value*> InOutArgs;
1913  std::vector<llvm::Type*> InOutArgTypes;
1914 
1915  // An inline asm can be marked readonly if it meets the following conditions:
1916  // - it doesn't have any sideeffects
1917  // - it doesn't clobber memory
1918  // - it doesn't return a value by-reference
1919  // It can be marked readnone if it doesn't have any input memory constraints
1920  // in addition to meeting the conditions listed above.
1921  bool ReadOnly = true, ReadNone = true;
1922 
1923  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1924  TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1925 
1926  // Simplify the output constraint.
1927  std::string OutputConstraint(S.getOutputConstraint(i));
1928  OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1929  getTarget(), &OutputConstraintInfos);
1930 
1931  const Expr *OutExpr = S.getOutputExpr(i);
1932  OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1933 
1934  OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1935  getTarget(), CGM, S,
1936  Info.earlyClobber());
1937 
1938  LValue Dest = EmitLValue(OutExpr);
1939  if (!Constraints.empty())
1940  Constraints += ',';
1941 
1942  // If this is a register output, then make the inline asm return it
1943  // by-value. If this is a memory result, return the value by-reference.
1944  if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1945  Constraints += "=" + OutputConstraint;
1946  ResultRegQualTys.push_back(OutExpr->getType());
1947  ResultRegDests.push_back(Dest);
1948  ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1949  ResultTruncRegTypes.push_back(ResultRegTypes.back());
1950 
1951  // If this output is tied to an input, and if the input is larger, then
1952  // we need to set the actual result type of the inline asm node to be the
1953  // same as the input type.
1954  if (Info.hasMatchingInput()) {
1955  unsigned InputNo;
1956  for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1957  TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1958  if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1959  break;
1960  }
1961  assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1962 
1963  QualType InputTy = S.getInputExpr(InputNo)->getType();
1964  QualType OutputType = OutExpr->getType();
1965 
1966  uint64_t InputSize = getContext().getTypeSize(InputTy);
1967  if (getContext().getTypeSize(OutputType) < InputSize) {
1968  // Form the asm to return the value as a larger integer or fp type.
1969  ResultRegTypes.back() = ConvertType(InputTy);
1970  }
1971  }
1972  if (llvm::Type* AdjTy =
1973  getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1974  ResultRegTypes.back()))
1975  ResultRegTypes.back() = AdjTy;
1976  else {
1977  CGM.getDiags().Report(S.getAsmLoc(),
1978  diag::err_asm_invalid_type_in_input)
1979  << OutExpr->getType() << OutputConstraint;
1980  }
1981 
1982  // Update largest vector width for any vector types.
1983  if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
1984  LargestVectorWidth = std::max(LargestVectorWidth,
1985  VT->getPrimitiveSizeInBits());
1986  } else {
1987  ArgTypes.push_back(Dest.getAddress().getType());
1988  Args.push_back(Dest.getPointer());
1989  Constraints += "=*";
1990  Constraints += OutputConstraint;
1991  ReadOnly = ReadNone = false;
1992  }
1993 
1994  if (Info.isReadWrite()) {
1995  InOutConstraints += ',';
1996 
1997  const Expr *InputExpr = S.getOutputExpr(i);
1998  llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1999  InOutConstraints,
2000  InputExpr->getExprLoc());
2001 
2002  if (llvm::Type* AdjTy =
2003  getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2004  Arg->getType()))
2005  Arg = Builder.CreateBitCast(Arg, AdjTy);
2006 
2007  // Update largest vector width for any vector types.
2008  if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2009  LargestVectorWidth = std::max(LargestVectorWidth,
2010  VT->getPrimitiveSizeInBits());
2011  if (Info.allowsRegister())
2012  InOutConstraints += llvm::utostr(i);
2013  else
2014  InOutConstraints += OutputConstraint;
2015 
2016  InOutArgTypes.push_back(Arg->getType());
2017  InOutArgs.push_back(Arg);
2018  }
2019  }
2020 
2021  // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2022  // to the return value slot. Only do this when returning in registers.
2023  if (isa<MSAsmStmt>(&S)) {
2024  const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2025  if (RetAI.isDirect() || RetAI.isExtend()) {
2026  // Make a fake lvalue for the return value slot.
2027  LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2029  *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2030  ResultRegDests, AsmString, S.getNumOutputs());
2031  SawAsmBlock = true;
2032  }
2033  }
2034 
2035  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2036  const Expr *InputExpr = S.getInputExpr(i);
2037 
2038  TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2039 
2040  if (Info.allowsMemory())
2041  ReadNone = false;
2042 
2043  if (!Constraints.empty())
2044  Constraints += ',';
2045 
2046  // Simplify the input constraint.
2047  std::string InputConstraint(S.getInputConstraint(i));
2048  InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2049  &OutputConstraintInfos);
2050 
2051  InputConstraint = AddVariableConstraints(
2052  InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2053  getTarget(), CGM, S, false /* No EarlyClobber */);
2054 
2055  llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2056 
2057  // If this input argument is tied to a larger output result, extend the
2058  // input to be the same size as the output. The LLVM backend wants to see
2059  // the input and output of a matching constraint be the same size. Note
2060  // that GCC does not define what the top bits are here. We use zext because
2061  // that is usually cheaper, but LLVM IR should really get an anyext someday.
2062  if (Info.hasTiedOperand()) {
2063  unsigned Output = Info.getTiedOperand();
2064  QualType OutputType = S.getOutputExpr(Output)->getType();
2065  QualType InputTy = InputExpr->getType();
2066 
2067  if (getContext().getTypeSize(OutputType) >
2068  getContext().getTypeSize(InputTy)) {
2069  // Use ptrtoint as appropriate so that we can do our extension.
2070  if (isa<llvm::PointerType>(Arg->getType()))
2071  Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2072  llvm::Type *OutputTy = ConvertType(OutputType);
2073  if (isa<llvm::IntegerType>(OutputTy))
2074  Arg = Builder.CreateZExt(Arg, OutputTy);
2075  else if (isa<llvm::PointerType>(OutputTy))
2076  Arg = Builder.CreateZExt(Arg, IntPtrTy);
2077  else {
2078  assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2079  Arg = Builder.CreateFPExt(Arg, OutputTy);
2080  }
2081  }
2082  }
2083  if (llvm::Type* AdjTy =
2084  getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2085  Arg->getType()))
2086  Arg = Builder.CreateBitCast(Arg, AdjTy);
2087  else
2088  CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2089  << InputExpr->getType() << InputConstraint;
2090 
2091  // Update largest vector width for any vector types.
2092  if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2093  LargestVectorWidth = std::max(LargestVectorWidth,
2094  VT->getPrimitiveSizeInBits());
2095 
2096  ArgTypes.push_back(Arg->getType());
2097  Args.push_back(Arg);
2098  Constraints += InputConstraint;
2099  }
2100 
2101  // Append the "input" part of inout constraints last.
2102  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2103  ArgTypes.push_back(InOutArgTypes[i]);
2104  Args.push_back(InOutArgs[i]);
2105  }
2106  Constraints += InOutConstraints;
2107 
2108  // Clobbers
2109  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2110  StringRef Clobber = S.getClobber(i);
2111 
2112  if (Clobber == "memory")
2113  ReadOnly = ReadNone = false;
2114  else if (Clobber != "cc")
2115  Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2116 
2117  if (!Constraints.empty())
2118  Constraints += ',';
2119 
2120  Constraints += "~{";
2121  Constraints += Clobber;
2122  Constraints += '}';
2123  }
2124 
2125  // Add machine specific clobbers
2126  std::string MachineClobbers = getTarget().getClobbers();
2127  if (!MachineClobbers.empty()) {
2128  if (!Constraints.empty())
2129  Constraints += ',';
2130  Constraints += MachineClobbers;
2131  }
2132 
2133  llvm::Type *ResultType;
2134  if (ResultRegTypes.empty())
2135  ResultType = VoidTy;
2136  else if (ResultRegTypes.size() == 1)
2137  ResultType = ResultRegTypes[0];
2138  else
2139  ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2140 
2141  llvm::FunctionType *FTy =
2142  llvm::FunctionType::get(ResultType, ArgTypes, false);
2143 
2144  bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2145  llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2146  llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2147  llvm::InlineAsm *IA =
2148  llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2149  /* IsAlignStack */ false, AsmDialect);
2150  llvm::CallInst *Result =
2151  Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2152  Result->addAttribute(llvm::AttributeList::FunctionIndex,
2153  llvm::Attribute::NoUnwind);
2154 
2155  // Attach readnone and readonly attributes.
2156  if (!HasSideEffect) {
2157  if (ReadNone)
2158  Result->addAttribute(llvm::AttributeList::FunctionIndex,
2159  llvm::Attribute::ReadNone);
2160  else if (ReadOnly)
2161  Result->addAttribute(llvm::AttributeList::FunctionIndex,
2162  llvm::Attribute::ReadOnly);
2163  }
2164 
2165  // Slap the source location of the inline asm into a !srcloc metadata on the
2166  // call.
2167  if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2168  Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2169  *this));
2170  } else {
2171  // At least put the line number on MS inline asm blobs.
2172  auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2173  Result->setMetadata("srcloc",
2174  llvm::MDNode::get(getLLVMContext(),
2175  llvm::ConstantAsMetadata::get(Loc)));
2176  }
2177 
2178  if (getLangOpts().assumeFunctionsAreConvergent()) {
2179  // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
2180  // convergent (meaning, they may call an intrinsically convergent op, such
2181  // as bar.sync, and so can't have certain optimizations applied around
2182  // them).
2183  Result->addAttribute(llvm::AttributeList::FunctionIndex,
2184  llvm::Attribute::Convergent);
2185  }
2186 
2187  // Extract all of the register value results from the asm.
2188  std::vector<llvm::Value*> RegResults;
2189  if (ResultRegTypes.size() == 1) {
2190  RegResults.push_back(Result);
2191  } else {
2192  for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2193  llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2194  RegResults.push_back(Tmp);
2195  }
2196  }
2197 
2198  assert(RegResults.size() == ResultRegTypes.size());
2199  assert(RegResults.size() == ResultTruncRegTypes.size());
2200  assert(RegResults.size() == ResultRegDests.size());
2201  for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2202  llvm::Value *Tmp = RegResults[i];
2203 
2204  // If the result type of the LLVM IR asm doesn't match the result type of
2205  // the expression, do the conversion.
2206  if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2207  llvm::Type *TruncTy = ResultTruncRegTypes[i];
2208 
2209  // Truncate the integer result to the right size, note that TruncTy can be
2210  // a pointer.
2211  if (TruncTy->isFloatingPointTy())
2212  Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2213  else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2214  uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2215  Tmp = Builder.CreateTrunc(Tmp,
2216  llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2217  Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2218  } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2219  uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2220  Tmp = Builder.CreatePtrToInt(Tmp,
2221  llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2222  Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2223  } else if (TruncTy->isIntegerTy()) {
2224  Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2225  } else if (TruncTy->isVectorTy()) {
2226  Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2227  }
2228  }
2229 
2230  EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2231  }
2232 }
2233 
2235  const RecordDecl *RD = S.getCapturedRecordDecl();
2236  QualType RecordTy = getContext().getRecordType(RD);
2237 
2238  // Initialize the captured struct.
2239  LValue SlotLV =
2240  MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2241 
2242  RecordDecl::field_iterator CurField = RD->field_begin();
2244  E = S.capture_init_end();
2245  I != E; ++I, ++CurField) {
2246  LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2247  if (CurField->hasCapturedVLAType()) {
2248  auto VAT = CurField->getCapturedVLAType();
2249  EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2250  } else {
2251  EmitInitializerForField(*CurField, LV, *I);
2252  }
2253  }
2254 
2255  return SlotLV;
2256 }
2257 
2258 /// Generate an outlined function for the body of a CapturedStmt, store any
2259 /// captured variables into the captured struct, and call the outlined function.
2260 llvm::Function *
2262  LValue CapStruct = InitCapturedStruct(S);
2263 
2264  // Emit the CapturedDecl
2265  CodeGenFunction CGF(CGM, true);
2266  CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2267  llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2268  delete CGF.CapturedStmtInfo;
2269 
2270  // Emit call to the helper function.
2271  EmitCallOrInvoke(F, CapStruct.getPointer());
2272 
2273  return F;
2274 }
2275 
2277  LValue CapStruct = InitCapturedStruct(S);
2278  return CapStruct.getAddress();
2279 }
2280 
2281 /// Creates the outlined function for a CapturedStmt.
2282 llvm::Function *
2284  assert(CapturedStmtInfo &&
2285  "CapturedStmtInfo should be set when generating the captured function");
2286  const CapturedDecl *CD = S.getCapturedDecl();
2287  const RecordDecl *RD = S.getCapturedRecordDecl();
2288  SourceLocation Loc = S.getBeginLoc();
2289  assert(CD->hasBody() && "missing CapturedDecl body");
2290 
2291  // Build the argument list.
2292  ASTContext &Ctx = CGM.getContext();
2293  FunctionArgList Args;
2294  Args.append(CD->param_begin(), CD->param_end());
2295 
2296  // Create the function declaration.
2297  const CGFunctionInfo &FuncInfo =
2298  CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2299  llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2300 
2301  llvm::Function *F =
2304  CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2305  if (CD->isNothrow())
2306  F->addFnAttr(llvm::Attribute::NoUnwind);
2307 
2308  // Generate the function.
2309  StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2310  CD->getBody()->getBeginLoc());
2311  // Set the context parameter in CapturedStmtInfo.
2312  Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2314 
2315  // Initialize variable-length arrays.
2317  Ctx.getTagDeclType(RD));
2318  for (auto *FD : RD->fields()) {
2319  if (FD->hasCapturedVLAType()) {
2320  auto *ExprArg =
2322  .getScalarVal();
2323  auto VAT = FD->getCapturedVLAType();
2324  VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2325  }
2326  }
2327 
2328  // If 'this' is captured, load it into CXXThisValue.
2331  LValue ThisLValue = EmitLValueForField(Base, FD);
2332  CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2333  }
2334 
2335  PGO.assignRegionCounters(GlobalDecl(CD), F);
2336  CapturedStmtInfo->EmitBody(*this, CD->getBody());
2338 
2339  return F;
2340 }
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:657
bool isAggregate() const
Definition: CGValue.h:54
const llvm::DataLayout & getDataLayout() const
Expr * getInc()
Definition: Stmt.h:2053
void EmitIndirectGotoStmt(const IndirectGotoStmt &S)
Definition: CGStmt.cpp:579
void EmitCoroutineBody(const CoroutineBodyStmt &S)
virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S)
Emit the captured statement body.
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:2458
Stmt * body_back()
Definition: Stmt.h:1062
body_iterator body_end()
Definition: Stmt.h:1059
void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S)
unsigned getNumInputs() const
Definition: Stmt.h:2374
SourceLocation getBeginLoc() const
Definition: Stmt.h:2285
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
A (possibly-)qualified type.
Definition: Type.h:642
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument.
Definition: Stmt.h:3062
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
const CodeGenOptions & getCodeGenOpts() const
static CSFC_Result CollectStatementsForCase(const Stmt *S, const SwitchCase *Case, bool &FoundCase, SmallVectorImpl< const Stmt *> &ResultStmts)
Definition: CGStmt.cpp:1345
void EmitGotoStmt(const GotoStmt &S)
Definition: CGStmt.cpp:568
void EmitAttributedStmt(const AttributedStmt &S)
Definition: CGStmt.cpp:564
param_iterator param_begin() const
Retrieve an iterator pointing to the first parameter decl.
Definition: Decl.h:4133
Address CreateMemTemp(QualType T, const Twine &Name="tmp", Address *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition: CGExpr.cpp:139
void enterFullExpression(const FullExpr *E)
Expr * getCond()
Definition: Stmt.h:1895
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
void EmitOMPDistributeDirective(const OMPDistributeDirective &S)
void EmitCXXTryStmt(const CXXTryStmt &S)
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
Stmt - This represents one statement.
Definition: Stmt.h:66
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1470
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
Definition: Expr.cpp:1104
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
Definition: EHScopeStack.h:384
bool requiresCleanups() const
Determine whether this scope requires any cleanups.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1019
void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S)
unsigned getNumOutputs() const
Definition: Stmt.h:2352
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
bool isNothrow() const
Definition: Decl.cpp:4483
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
Represents an attribute applied to a statement.
Definition: Stmt.h:1416
void EmitOMPOrderedDirective(const OMPOrderedDirective &S)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition: CGExpr.cpp:1910
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
Address GenerateCapturedStmtArgument(const CapturedStmt &S)
Definition: CGStmt.cpp:2276
bool validateInputConstraint(MutableArrayRef< ConstraintInfo > OutputConstraints, ConstraintInfo &info) const
Definition: TargetInfo.cpp:623
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1292
const RecordDecl * getCapturedRecordDecl() const
Retrieve the record declaration for captured variables.
Definition: Stmt.h:3006
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:379
llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, ArrayRef< llvm::Value *> Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition: CGCall.cpp:3766
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference...
Definition: CGExpr.cpp:3981
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant, or if it does but contains a label, return false.
Represents a point when we exit a loop.
Definition: ProgramPoint.h:715
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:345
void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S)
Stmt * getSubStmt()
Definition: Stmt.h:1338
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Represents a variable declaration or definition.
Definition: Decl.h:812
void EmitOMPCriticalDirective(const OMPCriticalDirective &S)
const VarDecl * getNRVOCandidate() const
Retrieve the variable that might be used for the named return value optimization. ...
Definition: Stmt.h:2268
uint64_t getProfileCount(const Stmt *S)
Get the profiler&#39;s count for the given statement.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope, by being a (possibly-labelled) DeclStmt.
DiagnosticsEngine & getDiags() const
void EmitLabel(const LabelDecl *D)
EmitLabel - Emit the block for the given label.
Definition: CGStmt.cpp:509
Stmt * getThen()
Definition: Stmt.h:1557
void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S)
void SimplifyForwardingBlocks(llvm::BasicBlock *BB)
SimplifyForwardingBlocks - If the given basic block is only a branch to another basic block...
Definition: CGStmt.cpp:421
The collection of all-type qualifiers we support.
Definition: Type.h:141
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
void EmitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective &S)
bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const
isObviouslyBranchWithoutCleanups - Return true if a branch to the specified destination obviously has...
Definition: CGCleanup.cpp:1025
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1376
void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S)
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
Definition: CGStmt.cpp:498
Represents a struct/union/class.
Definition: Decl.h:3602
const TargetInfo & getTarget() const
void EmitOMPSimdDirective(const OMPSimdDirective &S)
Stmt * getBody()
Definition: Stmt.h:1993
void setScopeDepth(EHScopeStack::stable_iterator depth)
Address getAddress() const
Definition: CGValue.h:327
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
StringRef getNormalizedGCCRegisterName(StringRef Name, bool ReturnCanonical=false) const
Returns the "normalized" GCC register name.
Definition: TargetInfo.cpp:485
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition: CGExpr.cpp:589
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:877
field_range fields() const
Definition: Decl.h:3793
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
Represents a member of a struct/union/class.
Definition: Decl.h:2588
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:4118
void rescopeLabels()
Change the cleanup scope of the labels in this lexical scope to match the scope of the enclosing cont...
Definition: CGStmt.cpp:537
static bool FindCaseStatementsForValue(const SwitchStmt &S, const llvm::APSInt &ConstantCondValue, SmallVectorImpl< const Stmt *> &ResultStmts, ASTContext &C, const SwitchCase *&ResultCase)
FindCaseStatementsForValue - Find the case statement being jumped to and then invoke CollectStatement...
Definition: CGStmt.cpp:1500
bool isReferenceType() const
Definition: Type.h:6294
Stmt *const * const_body_iterator
Definition: Stmt.h:1071
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:514
void EmitForStmt(const ForStmt &S, ArrayRef< const Attr *> Attrs=None)
Definition: CGStmt.cpp:827
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
void EmitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective &S)
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init)
Definition: CGClass.cpp:666
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition: CGExpr.cpp:194
IndirectGotoStmt - This represents an indirect goto.
Definition: Stmt.h:2122
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.cpp:4480
static bool hasScalarEvaluationKind(QualType T)
bool hasMatchingInput() const
Return true if this output operand has a matching (tied) input operand.
Definition: TargetInfo.h:827
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: Stmt.h:3049
void EmitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective &S)
ForStmt - This represents a &#39;for (init;cond;inc)&#39; stmt.
Definition: Stmt.h:2020
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
void pop()
End the current loop.
Definition: CGLoopInfo.cpp:325
LabelDecl * getDecl() const
Definition: Stmt.h:1393
SourceLocation getLBracLoc() const
Definition: Stmt.h:1116
void EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S)
RAII for correct setting/restoring of CapturedStmtInfo.
const Expr * getOutputExpr(unsigned i) const
Definition: Stmt.cpp:385
param_iterator param_end() const
Retrieve an iterator one past the last parameter decl.
Definition: Decl.h:4135
Stmt * getBody()
Definition: Stmt.h:2054
void EmitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective &S)
void EmitContinueStmt(const ContinueStmt &S)
Definition: CGStmt.cpp:1127
void EmitOMPTargetDirective(const OMPTargetDirective &S)
bool hasNormalCleanups() const
Determines whether there are any normal cleanups on the stack.
Definition: EHScopeStack.h:350
Stmt * getInit()
Definition: Stmt.h:2033
CXXForRangeStmt - This represents C++0x [stmt.ranged]&#39;s ranged for statement, represented as &#39;for (ra...
Definition: StmtCXX.h:127
bool IsOutlinedSEHHelper
True if the current function is an outlined SEH helper.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S)
void EmitSwitchStmt(const SwitchStmt &S)
Definition: CGStmt.cpp:1553
If a crash happens while one of these objects are live, the message is printed out along with the spe...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
field_iterator field_begin() const
Definition: Decl.cpp:4159
CaseStmt - Represent a case statement.
Definition: Stmt.h:1177
Expr * getCond()
Definition: Stmt.h:2052
void EmitOMPParallelDirective(const OMPParallelDirective &S)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition: CGExpr.cpp:182
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
Definition: CodeGenPGO.cpp:755
llvm::Function * EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K)
Generate an outlined function for the body of a CapturedStmt, store any captured variables into the c...
Definition: CGStmt.cpp:2261
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
void EmitDefaultStmt(const DefaultStmt &S)
Definition: CGStmt.cpp:1303
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitCaseStmtRange(const CaseStmt &S)
EmitCaseStmtRange - If case statement range is not too big then add multiple cases to switch instruct...
Definition: CGStmt.cpp:1142
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler&#39;s counter for the given statement by StepV.
uint64_t getCurrentProfileCount()
Get the profiler&#39;s current count.
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4053
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition: Stmt.cpp:902
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:71
Stmt * getBody()
Definition: Stmt.h:1741
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:440
Stmt * getInit()
Definition: Stmt.h:1613
LValue EmitLValueForField(LValue Base, const FieldDecl *Field)
Definition: CGExpr.cpp:3853
bool isValid() const
Definition: Address.h:36
StringRef getString() const
Definition: Expr.h:1660
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1024
void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S)
const TargetCodeGenInfo & getTargetCodeGenInfo()
Expr * IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY
IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the value (including ptr->int ...
Definition: Expr.cpp:2692
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition: CGExpr.cpp:223
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
bool isConstexpr() const
Definition: Stmt.h:1643
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
std::string generateAsmString(const ASTContext &C) const
Assemble final IR asm string.
Definition: Stmt.cpp:369
Exposes information about the current target.
Definition: TargetInfo.h:54
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
EHScopeStack::stable_iterator getScopeDepth() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:106
DeclStmt * getEndStmt()
Definition: StmtCXX.h:158
static Address invalid()
Definition: Address.h:35
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
void EmitCaseStmt(const CaseStmt &S)
Definition: CGStmt.cpp:1220
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:66
void EmitOMPTeamsDirective(const OMPTeamsDirective &S)
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition: CGStmt.cpp:370
LabelDecl * getConstantTarget()
getConstantTarget - Returns the fixed target of this indirect goto, if one exists.
Definition: Stmt.cpp:1043
Stmt * getBody()
Definition: Stmt.h:1907
void EmitSEHTryStmt(const SEHTryStmt &S)
Expr * getRHS()
Definition: Stmt.h:1278
static llvm::MDNode * getAsmSrcLocInfo(const StringLiteral *Str, CodeGenFunction &CGF)
getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline asm call instruction...
Definition: CGStmt.cpp:1845
llvm::LLVMContext & getLLVMContext()
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
Definition: CGCall.cpp:3696
llvm::BasicBlock * GetIndirectGotoBlock()
QualType getType() const
Definition: Expr.h:128
void EmitOMPMasterDirective(const OMPMasterDirective &S)
LabelDecl * getLabel() const
Definition: Stmt.h:2100
llvm::Function * GenerateCapturedStmtFunction(const CapturedStmt &S)
Creates the outlined function for a CapturedStmt.
Definition: CGStmt.cpp:2283
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2226
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
QualType getRecordType(const RecordDecl *Decl) const
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:1798
void ResolveBranchFixups(llvm::BasicBlock *Target)
Definition: CGCleanup.cpp:385
SourceLocation getEnd() const
void EmitOMPBarrierDirective(const OMPBarrierDirective &S)
StringRef getClobber(unsigned i) const
Definition: Stmt.cpp:409
Expr * getCond()
Definition: Stmt.h:1545
ValueDecl * getDecl()
Definition: Expr.h:1125
const LangOptions & getLangOpts() const
ASTContext & getContext() const
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:136
const SourceManager & SM
Definition: Format.cpp:1490
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D)
Emit simple code for OpenMP directives in Simd-only mode.
DoStmt - This represents a &#39;do/while&#39; stmt.
Definition: Stmt.h:1968
AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
Definition: Stmt.h:2303
void EmitDeclStmt(const DeclStmt &S)
Definition: CGStmt.cpp:1105
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:985
The l-value was considered opaque, so the alignment was determined from a type.
void EmitOMPFlushDirective(const OMPFlushDirective &S)
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
StringRef getInputConstraint(unsigned i) const
getInputConstraint - Return the specified input constraint.
Definition: Stmt.cpp:393
This captures a statement into a function.
Definition: Stmt.h:2888
StringRef getOutputConstraint(unsigned i) const
getOutputConstraint - Return the constraint string for the specified output operand.
Definition: Stmt.cpp:377
Encodes a location in the source.
void EmitDoStmt(const DoStmt &S, ArrayRef< const Attr *> Attrs=None)
Definition: CGStmt.cpp:765
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
Expr * getRetValue()
Definition: Stmt.h:2259
void EmitOMPForDirective(const OMPForDirective &S)
A saved depth on the scope stack.
Definition: EHScopeStack.h:107
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition: CGExpr.cpp:164
AggValueSlot::Overlap_t overlapForReturnValue()
Determine whether a return value slot may overlap some other object.
Expr * getLHS()
Definition: Stmt.h:1266
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
Definition: CGObjC.cpp:1532
Stmt * getElse()
Definition: Stmt.h:1566
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:926
Represents the declaration of a label.
Definition: Decl.h:468
An aggregate value slot.
Definition: CGValue.h:437
Expr * getCond()
Definition: Stmt.h:1729
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:46
void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S)
void EmitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective &S)
bool validateOutputConstraint(ConstraintInfo &Info) const
Definition: TargetInfo.cpp:526
void EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1752
void EmitOMPSingleDirective(const OMPSingleDirective &S)
An aligned address.
Definition: Address.h:25
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void EmitOMPForSimdDirective(const OMPForSimdDirective &S)
void EmitOMPAtomicDirective(const OMPAtomicDirective &S)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitOMPSectionDirective(const OMPSectionDirective &S)
void EmitOMPSectionsDirective(const OMPSectionsDirective &S)
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:965
void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S)
const CGFunctionInfo * CurFnInfo
void EmitDecl(const Decl &D)
EmitDecl - Emit a declaration.
Definition: CGDecl.cpp:42
const TargetCodeGenInfo & getTargetHooks() const
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
void EmitWhileStmt(const WhileStmt &S, ArrayRef< const Attr *> Attrs=None)
Definition: CGStmt.cpp:677
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:356
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:59
LabelStmt * getStmt() const
Definition: Decl.h:492
void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S)
Definition: CGObjC.cpp:1829
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn&#39;t support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S)
Dataflow Directional Tag Classes.
bool isVolatile() const
Definition: Stmt.h:2339
void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S)
LValue InitCapturedStruct(const CapturedStmt &S)
Definition: CGStmt.cpp:2234
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1021
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S)
void EmitOMPParallelForDirective(const OMPParallelForDirective &S)
ArrayRef< const Attr * > getAttrs() const
Definition: Stmt.h:1452
CSFC_Result
CollectStatementsForCase - Given the body of a &#39;switch&#39; statement and a constant value that is being ...
Definition: CGStmt.cpp:1344
void push(llvm::BasicBlock *Header, const llvm::DebugLoc &StartLoc, const llvm::DebugLoc &EndLoc)
Begin a new structured loop.
void EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S)
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
StmtClass getStmtClass() const
Definition: Stmt.h:812
void EmitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective &S)
void EmitOMPCancelDirective(const OMPCancelDirective &S)
bool hasTiedOperand() const
Return true if this input operand is a matching constraint that ties it to an output operand...
Definition: TargetInfo.h:834
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:3080
llvm::Module & getModule() const
void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
Definition: CGObjC.cpp:1825
body_iterator body_begin()
Definition: Stmt.h:1058
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2017
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Definition: CGExprAgg.cpp:1777
void EmitCoreturnStmt(const CoreturnStmt &S)
JumpDest ReturnBlock
ReturnBlock - Unified return block.
virtual StringRef getHelperName() const
Get the name of the capture helper.
static bool hasAggregateEvaluationKind(QualType T)
SwitchStmt - This represents a &#39;switch&#39; stmt.
Definition: Stmt.h:1669
API for captured statement code generation.
static std::string SimplifyConstraint(const char *Constraint, const TargetInfo &Target, SmallVectorImpl< TargetInfo::ConstraintInfo > *OutCons=nullptr)
Definition: CGStmt.cpp:1702
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
When instrumenting to collect profile data, the counts for some blocks such as switch cases need to n...
bool resolveSymbolicName(const char *&Name, ArrayRef< ConstraintInfo > OutputConstraints, unsigned &Index) const
Definition: TargetInfo.cpp:600
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
T * getAttr() const
Definition: DeclBase.h:527
void EmitAsmStmt(const AsmStmt &S)
Definition: CGStmt.cpp:1872
static std::string AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, const TargetInfo &Target, CodeGenModule &CGM, const AsmStmt &Stmt, const bool EarlyClobber)
AddVariableConstraints - Look at AsmExpr and if it is a variable declared as using a particular regis...
Definition: CGStmt.cpp:1755
Stmt * getInit()
Definition: Stmt.h:1750
decl_range decls()
Definition: Stmt.h:969
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
const Expr * getInputExpr(unsigned i) const
Definition: Stmt.cpp:401
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:32
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:443
void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S)
unsigned getNumClobbers() const
Definition: Stmt.h:2384
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2069
SourceManager & getSourceManager()
Definition: ASTContext.h:661
void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S)
DeclStmt * getRangeStmt()
Definition: StmtCXX.h:154
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
Definition: CGStmt.cpp:36
SourceLocation getAsmLoc() const
Definition: Stmt.h:2333
GotoStmt - This represents a direct goto.
Definition: Stmt.h:2087
Expr * getTarget()
Definition: Stmt.h:2142
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1152
CapturedDecl * getCapturedDecl()
Retrieve the outlined function declaration.
Definition: Stmt.cpp:1265
void setCurrentStmt(const Stmt *S)
If the execution count for the current statement is known, record that as the current count...
Definition: CodeGenPGO.h:74
Expr * getCond()
Definition: Stmt.h:1986
llvm::DenseMap< const VarDecl *, llvm::Value * > NRVOFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:864
void EmitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective &S)
void EmitIfStmt(const IfStmt &S)
Definition: CGStmt.cpp:600
ContinueStmt - This represents a continue.
Definition: Stmt.h:2167
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block, taking care to avoid creation of branches from dummy blocks.
Definition: CGStmt.cpp:463
bool isNRVOVariable() const
Determine whether this local variable can be used with the named return value optimization (NRVO)...
Definition: Decl.h:1324
bool isVoidType() const
Definition: Type.h:6530
void EmitReturnStmt(const ReturnStmt &S)
EmitReturnStmt - Note that due to GCC extensions, this can have an operand if the function returns vo...
Definition: CGStmt.cpp:1021
llvm::Type * ConvertType(QualType T)
virtual llvm::Type * adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, StringRef Constraint, llvm::Type *Ty) const
Corrects the low-level LLVM type for a given constraint and "usual" type.
Definition: TargetInfo.h:128
WhileStmt - This represents a &#39;while&#39; stmt.
Definition: Stmt.h:1846
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1232
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitLabelStmt(const LabelStmt &S)
Definition: CGStmt.cpp:559
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition: CGExpr.cpp:1756
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1577
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2407
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
virtual void addReturnRegisterOutputs(CodeGen::CodeGenFunction &CGF, CodeGen::LValue ReturnValue, std::string &Constraints, std::vector< llvm::Type *> &ResultRegTypes, std::vector< llvm::Type *> &ResultTruncRegTypes, std::vector< CodeGen::LValue > &ResultRegDests, std::string &AsmString, unsigned NumOutputs) const
Adds constraints and types for result registers.
Definition: TargetInfo.h:135
CGCapturedStmtInfo * CapturedStmtInfo
__DEVICE__ int max(int __a, int __b)
void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S)
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
Definition: CGExprAgg.cpp:1823
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1042
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
bool EmitSimpleStmt(const Stmt *S)
EmitSimpleStmt - Try to emit a "simple" statement which does not necessarily require an insertion poi...
Definition: CGStmt.cpp:347
BreakStmt - This represents a break.
Definition: Stmt.h:2193
void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S)
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:17
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1050
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:732
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:2787
Stmt * getSubStmt()
Definition: Stmt.h:1397
void EmitCXXForRangeStmt(const CXXForRangeStmt &S, ArrayRef< const Attr *> Attrs=None)
Definition: CGStmt.cpp:926
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition: CGStmt.cpp:382
void EmitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective &S)
DeclStmt * getLoopVarStmt()
Definition: StmtCXX.h:161
A trivial tuple used to represent a source range.
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
Definition: CGObjC.cpp:1821
LValue - This represents an lvalue references.
Definition: CGValue.h:167
SanitizerMetadata * getSanitizerMetadata()
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
Definition: CGStmt.cpp:480
APSInt & getInt()
Definition: APValue.h:252
const LangOptions & getLangOpts() const
DeclStmt * getBeginStmt()
Definition: StmtCXX.h:155
void EmitBreakStmt(const BreakStmt &S)
Definition: CGStmt.cpp:1115
void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S)
Definition: CGObjC.cpp:3259
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
SourceLocation getBegin() const
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument.
Definition: Stmt.h:3072
llvm::Value * getPointer() const
Definition: CGValue.h:323
This class handles loading and caching of source files into memory.
Stmt * getSubStmt()
Definition: Stmt.h:1456
bool haveRegionCounts() const
Whether or not we have PGO region data for the current function.
Definition: CodeGenPGO.h:51
Defines enum values for all the target-independent builtin functions.
void EmitOMPTaskDirective(const OMPTaskDirective &S)
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:906
CapturedRegionKind getCapturedRegionKind() const
Retrieve the captured region kind.
Definition: Stmt.cpp:1280
bool isScalar() const
Definition: CGValue.h:52
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:418
virtual std::string convertConstraint(const char *&Constraint) const
Definition: TargetInfo.h:932
void EmitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective &S)
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
virtual const char * getClobbers() const =0
Returns a string of target-specific clobbers, in LLVM format.
Stmt * getSubStmt()
Definition: Stmt.h:1296
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1548